Frank
Frank

Reputation: 2696

Find index of first element with condition in numpy array in python

I'm trying find the index of the first element bigger than a threshold, like this:

index = 0
while timeStamps[index] < self.stopCount and index < len(timeStamps):
    index += 1

Can this be done in a one-liner? I found:

index = next((x for x in timeStamps if x <= self.stopCount), 0)

I'm not sure what this expression does and it seems to return 0 always... Could somebody point out the error and explain the expression?

Upvotes: 3

Views: 3778

Answers (3)

Dev Khadka
Dev Khadka

Reputation: 5451

this one liner will work

sample_array = np.array([10,11,12,13,21,200,1,2])

# oneliner
print(sum(np.cumsum(arr>threshold)==0))

np.cumsum(sample_array>threshold)==0) will have value 0 until element is bigger than threshold

Upvotes: 0

tomjn
tomjn

Reputation: 5390

Another option is to use np.argmax (see this post for details). So your code would become something like

(timeStamps > self.stopCount).argmax()

the caveat is that if the condition is never satisfied the argmax will return 0.

Upvotes: 5

P&#233;ter Le&#233;h
P&#233;ter Le&#233;h

Reputation: 2119

I would do it this way:

import numpy as np

threshold = 20

sample_array = np.array([10,11,12,13,21,200,1,2])

idx = np.array([np.where(sample_array > threshold)]).min()
print(idx)
#4

Upvotes: 0

Related Questions