3

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?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Frank
  • 2,446
  • 7
  • 33
  • 67

3 Answers3

5

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.

tomjn
  • 5,100
  • 1
  • 9
  • 24
0

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
Péter Leéh
  • 2,069
  • 2
  • 10
  • 23
0

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

Dev Khadka
  • 5,142
  • 4
  • 19
  • 33