Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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]
like image 750
user1506145 Avatar asked Apr 24 '13 20:04

user1506145


People also ask

How do you access different rows of a multidimensional NumPy array?

In NumPy , it is very easy to access any rows of a multidimensional array. All we need to do is Slicing the array according to the given conditions. Whenever we need to perform analysis, slicing plays an important role.

Does NumPy arrays support boolean indexing?

We can also index NumPy arrays using a NumPy array of boolean values on one axis to specify the indices that we want to access. This will create a NumPy array of size 3x4 (3 rows and 4 columns) with values from 0 to 11 (value 12 not included).

How do I select part of an array in NumPy?

Slice a Range of Values from Two-dimensional Numpy Arrays For example, you can use the index [0:1, 0:2] to select the elements in first row, first two columns. You can flip these index values to select elements in the first two rows, first column.

How do I get rows and columns of a NumPy array?

In the NumPy with the help of shape() function, we can find the number of rows and columns. In this function, we pass a matrix and it will return row and column number of the matrix. Return: The number of rows and columns.


1 Answers

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.

like image 95
Hooked Avatar answered Oct 20 '22 13:10

Hooked