I have a NumPy array, A
. I want to know the indexes of the elements in A equal to a value and which indexes satisfy some condition:
import numpy as np
A = np.array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
value = 2
ind = np.array([0, 1, 5, 10]) # Index belongs to ind
Here is what I did:
B = np.where(A==value)[0] # Gives the indexes in A for which value = 2
print(B)
[1 5 9]
mask = np.in1d(B, ind) # Gives the index values that belong to the ind array
print(mask)
array([ True, True, False], dtype=bool)
print B[mask] # Is the solution
[1 5]
The solution works, but I find it complicated. Also, in1d
does a sort which is slow. Is there a better way of achieving this?
Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
It returns a new numpy array, after filtering based on a condition, which is a numpy-like array of boolean values. For example, if condition is array([[True, True, False]]) , and our array is a = ndarray([[1, 2, 3]]) , on applying a condition to array ( a[:, condition] ), we will get the array ndarray([[1 2]]) .
If you flip the operation order around you can do it in one line:
B = ind[A[ind]==value]
print B
[1 5]
Breaking that down:
#subselect first
print A[ind]
[1 2 2 3]
#create a mask for the indices
print A[ind]==value
[False True True False]
print ind
[ 0 1 5 10]
print ind[A[ind]==value]
[1 5]
B = np.where(A==value)[0] #gives the indexes in A for which value = 2
print np.intersect1d(B, ind)
[1 5]
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