7

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.

2
  • 1
    labels is 2-d, but the index uses it as if it was 1-d. Commented Nov 23, 2013 at 18:36
  • 4
    Actually, the first indexing is wrong too, with numpy >=1.8. you will get the same error there too. Commented Nov 23, 2013 at 18:37

1 Answer 1

6

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, :]
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, I find 2D arrays better behaved for most np work. With a matlab background a lot of people default to using matrix vs array. BTW: I get the same behavior in 1.7.
labels.view(np.ndarray) changes the type of labels to np.ndarray while the ravel call flattens the array. Note ==1 can be ommited

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.