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?
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.
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).
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.
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.
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)
.
You should be able to use numpy.nonzero()
to find this information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With