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?

yatu
  • 86,083
  • 12
  • 84
  • 139
Al-Baraa El-Hag
  • 770
  • 6
  • 15

1 Answers1

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
yatu
  • 86,083
  • 12
  • 84
  • 139