Numpy first occurrence of value greater than existing value


I have a 1D array in numpy and I want to find the position of the index where a value exceeds the value in numpy array.


aa = range(-10,10)

Find position in aa where, the value 5 gets exceeded.

Answer rating: 237

This is a little faster (and looks nicer)


Since argmax will stop at the first True ("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn"t save another list.

In [2]: N = 10000

In [3]: aa = np.arange(-N,N)

In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop

In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop

In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop

Get Solution for free from DataCamp guru