Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements of numpy array via boolean mask array

I have a boolean mask array a of length n:

a = np.array([True, True, True, False, False]) 

I have a 2d array with n columns:

b = np.array([[1,2,3,4,5], [1,2,3,4,5]]) 

I want a new array which contains only the "True"-values, for example

c = ([[1,2,3], [1,2,3]]) 

c = a * b does not work because it contains also "0" for the false columns what I don't want

c = np.delete(b, a, 1) does not work 

Any suggestions?

like image 784
JohnDoe Avatar asked Nov 14 '13 17:11

JohnDoe


People also ask

How do you select a specific element in a numpy array?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.

What is boolean masking in numpy?

Boolean masking, also called boolean indexing, is a feature in Python NumPy that allows for the filtering of values in numpy arrays.

How do you make a boolean numpy array?

A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.

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


1 Answers

You probably want something like this:

>>> a = np.array([True, True, True, False, False]) >>> b = np.array([[1,2,3,4,5], [1,2,3,4,5]]) >>> b[:,a] array([[1, 2, 3],        [1, 2, 3]]) 

Note that for this kind of indexing to work, it needs to be an ndarray, like you were using, not a list, or it'll interpret the False and True as 0 and 1 and give you those columns:

>>> b[:,[True, True, True, False, False]]    array([[2, 2, 2, 1, 1],        [2, 2, 2, 1, 1]]) 
like image 184
DSM Avatar answered Sep 23 '22 03:09

DSM