Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding index of greatest element comparison in numpy array

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?

like image 553
jll Avatar asked Mar 10 '23 05:03

jll


1 Answers

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 nans in the computation):

>>> np.where(a < v, a, np.nan)
array([  0.,  50.,   5.,  52.,  nan])
like image 149
MSeifert Avatar answered Apr 02 '23 00:04

MSeifert