What is the best way to retrieve the index of the first element verifying a certain condition in a numpy array?
I could do the following
x = np.array([1, 2, 1, 2, 2, 2, 1, 1])
np.where(x == 2)[0][0]
Which would give me the index of the first occurrence of number 2 in the array.
This loops over the entire array, evaluating the condition x[i] == 2
for all i
in range(len(x))
to create a boolean mask which is then passed to np.where
to retrieve the indices of True
elements.
Looping over the entire array is not needed, the iteration could stop as soon as the first element verifying the condition is met.
Is there a numpy way to do this without iterating over the entire array?