将2D NumPy数组转换为1D数组以绘制直方图

问题描述:

我正在尝试使用matplotlib绘制直方图. 我需要转换我的单行2D数组

I'm trying to plot a histogram with matplotlib. I need to convert my one-line 2D Array

[[1,2,3,4]] # shape is (1,4)

插入一维数组

[1,2,3,4] # shape is (4,)

我该怎么做?

您可以直接为该列编制索引:

You can directly index the column:

>>> import numpy as np
>>> x2 = np.array([[1,2,3,4]])
>>> x2.shape
(1, 4)
>>> x1 = x2[0,:]
>>> x1
array([1, 2, 3, 4])
>>> x1.shape
(4,)

或者您可以使用挤压:

>>> xs = np.squeeze(x2)
>>> xs
array([1, 2, 3, 4])
>>> xs.shape
(4,)