0

I want a pretty way to find the index of the first element of an np.array, that matches some condition. The condition is:

array>constant

This is my solution:

first_index = ((array<constant)*np.arange(len(array))).argmax()+1

Is there a prettier one-line way to do this in numpy or python?

5
  • 2
    Well that solution is one-line. Why the +1? Perhaps argwhere? Commented Feb 8, 2019 at 18:49
  • But it's not pretty, and I was wondering it there is a prettier way Commented Feb 8, 2019 at 18:50
  • np.argwhere(array>constant)[0] works great, thanks! Commented Feb 8, 2019 at 18:53
  • Does your solution in the code actually works, it appears it returns the last index. Commented Feb 8, 2019 at 18:54
  • It returns the last index of the opposite condition(+1), I forgot to mention that Commented Feb 8, 2019 at 18:54

1 Answer 1

2

Argmax goes sequentially if you look at the document: so it will find the first true value

https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.argmax.html

So you could use

np.argmax(array<val)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, for my purposes I need np.argmin(), but the principle works. (I am looking for the opposite condition than the one in the expression).
@ShayLempert argmax simply finds the first element that has met the condition and is True. If you want it the other way around, switch the direction of inequality instead of using argmin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.