Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 328
Frank Avatar asked Feb 11 '26 21:02

Frank


1 Answers

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.

like image 135
tomjn Avatar answered Feb 14 '26 09:02

tomjn