1

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?

valentin
  • 2,596
  • 6
  • 28
  • 48
  • using a function with a for loop decreases `Wall time: 2.66 ms` to `Wall time: 1.69 ms` although it's not a native to `numpy` solution – gold_cy Apr 19 '17 at 14:56

0 Answers0