Numpy IndexError: Too many indexes for an array when indexing a matrix with another

I have a matrix a, which I create as follows:

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

I have matrix labels that I create like this:

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

Here's what the two matrices 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 are no problems

 >>> 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 anyone know why this is? I know that there are already similar questions to this, but none of them explains my problem well enough, and the answers do not help me.

+7
python arrays numpy matrix
source share
1 answer

Since labels is a matrix, when you do labels==1 , you get a logical matrix of the same form. Then executing a[labels==1, :] will return only the first column with rows matching the match. Please note that your intention to receive:

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

was not reached (you only have the first column), although it worked for NumPy <1.8 (as @seberg points out).

To get what you want, you can use the flattened view of labels :

 a[labels.view(np.ndarray).ravel()==1, :] 
+6
source share

All Articles