numpy的IndexError:数组太多指数与另一个索引矩阵时, [英] numpy IndexError: too many indices for array when indexing matrix with another
问题描述
我有一个矩阵,我创建这样的:
I have a matrix a which I create like this:
>>> a = np.matrix("1 2 3; 4 5 6; 7 8 9; 10 11 12")
我有我创建这样一个矩阵标签:
I have a matrix labels which I create like this:
>>> labels = np.matrix("1;0;1;1")
这是两个基质中的样子:
This is what the two matricies look like:
>>> a
matrix([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
>>> labels
matrix([[1],
[0],
[1],
[1]])
正如你所看到的,当我选择所有列,是没有问题的。
As you can see, when I select all columns, there is no problem
>>> a[labels == 1, :]
matrix([[ 1, 7, 10]])
但是,当我尝试指定一个专栏中,我得到一个错误
But when I try to specify a column I get an error
>>> 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
>>>
有谁知道这是为什么?
我知道有这已经类似的问题,但他们没有解释我的问题不够好,也不是有帮助的回答我。
Does anybody know why this is? I am aware there are similar questions to this already but none of them explain my problem well enough, neither are the answers helpful to me.
推荐答案
由于标签
是一个矩阵,当你做标签== 1
您获得相同形状的布尔矩阵。然后做 A [标签== 1:]
将返回您仅与对应的匹配行的第一列。请注意,您的意向得到:
Since labels
is a matrix when you do labels==1
you obtain a boolean matrix of the same shape. Then doing a[labels==1, :]
will return you only the first column with the lines corresponding to the match. Note that your intention to get:
matrix([[ 1, 2, 3],
[ 7, 8, 9],
[10, 11, 12]])
没有达到(你得到只有第一列),尽管它的工作对numpy的&下; 1.8(如由@seberg指出)。
was not achieved (you got only the first column), even though it worked for NumPy < 1.8 (as pointed out by @seberg).
为了得到你想要的,你可以使用标签
的平面视图是什么:
In order to get what you want you can use a flattened view of labels
:
a[labels.view(np.ndarray).ravel()==1, :]
这篇关于numpy的IndexError:数组太多指数与另一个索引矩阵时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!