Select rows in a two-dimensional Numpy Boolean vector array

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 zero.

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

How to do this so that it returns this string?

[10, 11, 12, 13, 14]
+5
source share
1 answer

The form is bsomewhat strange, but if you can create it as a more convenient index, this is a simple choice:

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

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

You can read it as: "select all rows where the index is 0, and for each row selected take all the columns." Your expected answer should be a list of lists, as you request all rows that match the criteria.

+2
source

All Articles