繁体   English   中英

numpy IndexError:当矩阵与另一个矩阵索引时,数组的索引太多

[英]numpy IndexError: too many indices for array when indexing matrix with another

我有一个矩阵,我这样创建:

>>> a = np.matrix("1 2 3; 4 5 6; 7 8 9; 10 11 12")

我有一个矩阵标签,我这样创建:

>>> labels = np.matrix("1;0;1;1")

这就是两个基质的样子:

>>> a
matrix([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])
>>> labels
matrix([[1],
        [0],
        [1],
        [1]])

如您所见,当我选择所有列时,没有问题

>>> a[labels == 1, :]
matrix([[ 1,  7, 10]])

但是当我尝试指定列时,我收到错误

>>> a[labels == 1, 1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 305, in     __getitem__
    out = N.ndarray.__getitem__(self, index)
IndexError: too many indices for array
>>>   

有谁知道这是为什么? 我知道有类似的问题,但没有一个能够很好地解释我的问题,答案也没有对我有帮助。

由于labels是一个矩阵,当你做labels==1你得到一个相同形状的布尔矩阵。 然后执行a[labels==1, :]返回第一列,其中包含与匹配相对应的行。 请注意您的意图:

matrix([[ 1,  2,  3],
        [ 7,  8,  9],
        [10, 11, 12]])

没有实现(你只得到了第一列),尽管它对NumPy <1.8起作用(正如@seberg所指出的那样)。

为了得到你想要的东西,你可以使用扁平的labels视图:

a[labels.view(np.ndarray).ravel()==1, :]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM