Finding the index of greatest comparison of elements in a numpy array

I have an array a

and I want to find the position of the largest element in a

that given value is even greater.

In this example:

a = np.array([0, 50, 5, 52, 60])
v = 55

      

largest element that is v

greater than 52

(index 3), so I want to return 3.

The numpy function argmax()

does not work for this purpose as it returns the first item. What's the quick and correct way to do this with numpy?

+3


source to share


2 answers


You can slice the array and find the maximum yourself, and then query its index:



np.where(a==a[a<v].max())
Out: (array([3]),)

      

+2


source


You can combine argmax

with where

:

>>> np.nanargmax(np.where(a < v, a, np.nan))
3

      



np.where

replaces all values ​​above v

with nan

before applying nanargmax

(which is ignored nan

in the calculation):

>>> np.where(a < v, a, np.nan)
array([  0.,  50.,   5.,  52.,  nan])

      

+3


source







All Articles