Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a boolean array into index array in numpy

Is there an efficient Numpy mechanism to retrieve the integer indexes of locations in an array based on a condition is true as opposed to the Boolean mask array?

For example:

x=np.array([range(100,1,-1)]) #generate a mask to find all values that are a power of 2 mask=x&(x-1)==0 #This will tell me those values print x[mask] 

In this case, I'd like to know the indexes i of mask where mask[i]==True. Is it possible to generate these without looping?

like image 361
Rich Avatar asked Nov 21 '11 20:11

Rich


People also ask

How do you use boolean indexing in NumPy?

You can index specific values from a NumPy array using another NumPy array of Boolean values on one axis to specify the indices you want to access. For example, to access the second and third values of array a = np. array([4, 6, 8]) , you can use the expression a[np.

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 you convert boolean to array?

To convert a Boolean array a to an integer array, use the a. astype(int) method call. The single argument int specifies the desired data type of each array item.

Can you index a boolean Python?

The Boolean values like True & false and 1&0 can be used as indexes in panda dataframe. They can help us filter out the required records. In the below exampels we will see different methods that can be used to carry out the Boolean indexing operations.


2 Answers

Another option:

In [13]: numpy.where(mask) Out[13]: (array([36, 68, 84, 92, 96, 98]),) 

which is the same thing as numpy.where(mask==True).

like image 172
Steve Tjoa Avatar answered Sep 18 '22 15:09

Steve Tjoa


You should be able to use numpy.nonzero() to find this information.

like image 41
aganders3 Avatar answered Sep 20 '22 15:09

aganders3