Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy argmax with max less than some number

Tags:

python

numpy

I have a numpy array as:

myArray
array([[ 1.    ,     nan,     nan,     nan,     nan],
       [ 1.    ,     nan,     nan,     nan,     nan],
       [ 0.63  ,  0.79  ,  1.    ,     nan,     nan],
       [ 0.25  ,  0.4   ,  0.64  ,  0.84  ,     nan]])

I need to find for each row, the column numbers for max value but the max has to be less than 1.

In the above array, row 0,1 should return Nan.

Row 2 should return 1.

Row 3 should return 3.

I am not sure how to condition this on argmax.

like image 589
Zanam Avatar asked Feb 10 '17 17:02

Zanam


People also ask

What is the difference between NP Max and NP argmax?

Essentially, the argmax function returns the index of the maximum value of a Numpy array. What is this? It's somewhat similar to the Numpy maximum function, but instead of returning the maximum value, it returns the index of the maximum value.

How do I get indices of N maximum values in a NumPy array?

For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy. argsort() function of NumPy then applying slicing concept with negative indexing. Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.

Can argmax return multiple values?

argmax() function returns the indices of the maximum values along an axis. In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence will be returned.

What does argmax () do in Python?

Returns the indices of the maximum values along an axis. Input array. By default, the index is into the flattened array, otherwise along the specified axis.


1 Answers

Here's one approach with np.where -

m = a < 1  # Mask of elems < 1 and non-NaNs

# Set NaNs and elems > 1 to global minimum values minus 1, 
# so that when used with argmax those would be ignored
idx0 = np.where(m, a,np.nanmin(a)-1).argmax(1)

# Look for rows with no non-NaN and < 1 elems and set those in o/p as NaNs
idx = np.where(m.any(1), idx0, np.nan)

Sample run -

In [97]: a
Out[97]: 
array([[ 1.  ,   nan,   nan,   nan,   nan],
       [ 1.  ,   nan,   nan,   nan,   nan],
       [ 0.63,  0.79,  1.  ,   nan,   nan],
       [ 0.25,  0.4 ,  0.64,  0.84,   nan]])

In [98]: m = a < 1

In [99]: idx0 = np.where(m, a,np.nanmin(a)-1).argmax(1)

In [100]: idx0
Out[100]: array([0, 0, 1, 3])

In [101]: np.where(m.any(1), idx0, np.nan)
Out[101]: array([ nan,  nan,   1.,   3.])
like image 99
Divakar Avatar answered Nov 03 '22 04:11

Divakar