2

So I've been looking all over on the internet, but I cannot find out how to do this without a for loop + if statement. Let's say that I have this as my array:

import numpy as np

a = np.array([361, 362, 363, 364, 365, 0, 1, 2, 366, 367])

I want to find out to find out the first highest value (regardless if there is another higher value in the future), which in this case would be 365. This is how I would do it without using numpy:

import numpy as np

a = np.array([361, 362, 363, 364, 365, 0, 1, 2, 366, 367])

for element in range(a.shape[0]-1):
    if a[element+1] < a[element]:
        first_max = a[element]
        break

print(first_max)
# 365

Is there a way to do this using a numpy function?

1
  • 1
    Dupe is a way more complicated question without the short-circuiting requirement Commented Nov 5, 2020 at 14:34

1 Answer 1

5

One way is taking the first differences, find the first negative value and obtain its index using argmax:

a[(np.diff(a) < 0).argmax()]
# 365

Though depending on the scenario, a generator and shortcircuiting in the first match might be better:

next(v0 for i,(v0,v1) in enumerate(zip(a[:-1], a[1:])) if v0>v1)
# 365
Sign up to request clarification or add additional context in comments.

Comments

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.