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?

3
  • 2
    Why is it important to write it in a one-liner? One liners produce the same machine code and are more difficult to understand and debug Commented Sep 3, 2019 at 10:35
  • Good point. I found it rather slow, but perhaps there is no faster way. It is merely for comparison. Commented Sep 3, 2019 at 10:37
  • More importantly, why are you using loops with numpy? Commented Sep 3, 2019 at 11:23

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what I want, including caveat.
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

1 Comment

Wrapping in an extra list and an array seem like total overkill here
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

1 Comment

This is such a convoluted way, but it sure does work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.