Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 760
lilroo Avatar asked Nov 23 '13 17:11

lilroo


1 Answers

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]])

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, :]
like image 112
Saullo G. P. Castro Avatar answered Sep 29 '22 09:09

Saullo G. P. Castro