I have an array a
and I want to find the position of largest element in a
that a given value is still greater than.
In this example:
a = np.array([0, 50, 5, 52, 60])
v = 55
the greatest element that v
is bigger than is 52
(index 3) so I want to return 3.
The numpy function argmax()
doesn't work for this purpose since it returns the first element. What is the fast and correct way to do this with numpy?
You can combine argmax
with where
:
>>> np.nanargmax(np.where(a < v, a, np.nan))
3
The np.where
replaces all values above v
to nan
before it applies nanargmax
(which ignores nan
s in the computation):
>>> np.where(a < v, a, np.nan)
array([ 0., 50., 5., 52., nan])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With