user1506145
user1506145

Reputation: 5286

Select rows in a Numpy 2D array with a boolean vector

I have a matrix and a boolean vector:

>>>from numpy import *
>>>a = arange(20).reshape(4,5)
array([[ 0,  1,  2,  3,  4],
   [ 5,  6,  7,  8,  9],
   [10, 11, 12, 13, 14],
   [15, 16, 17, 18, 19]])

>>>b = asarray( [1, 1, 0, 1] ).reshape(-1,1)
array([[1],
   [1],
   [0],
   [1]])

Now I want to select all the corresponding rows in this matrix where the corresponding index in the vector is equal to zero.

>>>a[b==0]
array([10])

How can I make it so this returns this particular row?

[10, 11, 12, 13, 14]

Upvotes: 12

Views: 11244

Answers (2)

Jonathan H
Jonathan H

Reputation: 7953

Nine years later, I just wanted to add another answer to this question in the case where b is actually a boolean vector.

Square bracket indexing of a Numpy matrix with scalar indices give the corresponding rows, so for example a[2] gives the third row of a. Multiple rows can be selected (potentially with repeats) using a vector of indices.

Similarly, logical vectors that have the same length as the number of rows act as "masks", for example:

a = np.arange(20).reshape(4,5)
b = np.array( [True, True, False, True] )

a[b] # 3x5 matrix formed with the first, second, and last row of a

To answer the OP specifically, the only thing to do from there is to negate the vector b:

a[ np.logical_not(b) ]

Lastly, if b is defined as in the OP with ones and zeros and a column shape, one would simply do: np.logical_not( b.ravel().astype(bool) ).

Upvotes: 0

Hooked
Hooked

Reputation: 88148

The shape of b is somewhat strange, but if you can craft it as a nicer index it's a simple selection:

idx = b.reshape(a.shape[0])
print a[idx==0,:]

>>> [[10 11 12 13 14]]

You can read this as, "select all the rows where the index is 0, and for each row selected take all the columns". Your expected answer should really be a list-of-lists since you are asking for all of the rows that match a criteria.

Upvotes: 6

Related Questions