user308827
user308827

Reputation: 21961

Find the nth time a specific value is exceeded in numpy array

This is an extension of the question asked here: Numpy first occurrence of value greater than existing value

N = 10000
aa = np.arange(-N,N)

In this numpy array, I want to find the index where the array exceeds 0 for the 10th time. To find where it exceeds 0 for the first time, I can simply do:

np.argmax(aa>0.0)

Upvotes: 1

Views: 2106

Answers (1)

perimosocordiae
perimosocordiae

Reputation: 17797

You can work from the same principles as the "first time" case, just with a slightly more complicated middle step.

Start with the boolean array representing your condition:

cond = aa > 0

Convert the True/False values in the array to counts:

counts = np.cumsum(cond)

Search for the first occurrence of the count you're looking for:

idx = np.searchsorted(counts, 10)

Remember that the 10 in this last line refers to the tenth value that satisfies the condition, and the first value has count 1.


Alternately, you could convert the condition array to indices:

indices, = np.nonzero(cond)
idx = indices[9]

Note that in this setup, the tenth value will be at index 9.

Upvotes: 4

Related Questions