"解包的价值太多"在numpy histogram2d

时间:2013-09-27 14:02:23

标签: python numpy histogram histogram2d

我使用numpy histogram2d来计算两个变量的二维直方图的直观表示的值:

H, xedges, yedges = np.histogram2d(Z[:,0], Z[:,1], bins=100)

其中Z是numpy矩阵

我得到的错误是:

Traceback (most recent call last):
File "/home/.../pca_analysis.py", line 141, in <module>
   H, xedges, yedges = np.histogram2d(Z[:,0], Z[:,1], bins=100)
File "/usr/lib/python2.7/dist-packages/numpy/lib/twodim_base.py", line 615, in histogram2d
   hist, edges = histogramdd([x,y], bins, range, normed, weights)
File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 281, in histogramdd
   N, D = sample.shape
ValueError: too many values to unpack

我无法理解为什么会收到此错误。我尝试使用随机值的histogram2d函数,它正常工作。我也尝试在numpy数组和简单列表中转换Z [:,0]和Z [:,1],但我遇到了同样的问题。

1 个答案:

答案 0 :(得分:6)

正如@seberg在评论中指出的那样,Z是一个矩阵,因此在切片之前必须将其转换为数组。

np.asarray(Z)[:,0]

这是必要的原因是因为np.matrix即使在切片后也保持其二维性,因此矩阵列的形状为(N,1),而不是直方图函数所期望的(N,)

在切片之后无法转换为数组的原因是通过强制转换来改变形状;切片的行为是不同的。

如果没有意义,这里有一个例子:

In [4]: a = np.arange(9).reshape(3,3)

In [5]: a
Out[5]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [6]: m = np.matrix(a)

In [7]: m
Out[7]: 
matrix([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])

In [8]: m[:,0]
Out[8]: 
matrix([[0],
        [3],
        [6]])

In [9]: a[:,0]
Out[9]: array([0, 3, 6])

In [10]: m[:,0].shape
Out[10]: (3, 1)

In [11]: a[:,0].shape
Out[11]: (3,)

如果你在切片后施放,形状仍然是2d:

In [12]: np.array(m[:,0])
Out[12]: 
array([[0],
       [3],
       [6]])

In [13]: np.array(m[:,0]).shape
Out[13]: (3, 1)