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

bio*_*ime 9 numpy matplotlib

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

[[1,2,3,4]] # shape is (1,4)
Run Code Online (Sandbox Code Playgroud)

进入1D阵列

[1,2,3,4] # shape is (4,)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

khs*_*ing 14

添加ravel为未来搜索者的另一种选择.从文档中,

它相当于重塑(-1,order = order).

由于数组是1xN,因此以下所有内容都是等效的:

  • arr1d = np.ravel(arr2d)
  • arr1d = arr2d.ravel()
  • arr1d = arr2d.flatten()
  • arr1d = np.reshape(arr2d, -1)
  • arr1d = arr2d.reshape(-1)
  • arr1d = arr2d[0, :]


mtr*_*trw 10

您可以直接索引列:

>>> 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,)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用挤压:

>>> xs = np.squeeze(x2)
>>> xs
array([1, 2, 3, 4])
>>> xs.shape
(4,)
Run Code Online (Sandbox Code Playgroud)