Search code examples
pythonnumpynumpy-ndarrayargmax

Python: nanargmax version for ndarray


I'm super new to Python. I have a multidimensional array which contains NaNs. How do I get the index of the maximum value in the array?

I tried using numpy.nanargmax(), but it seems that I can't use nanargmax with an ndarray?

>>> a=np.arange(24).reshape(6,4).astype('float')
>>> a
array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.],
       [12., 13., 14., 15.],
       [16., 17., 18., 19.],
       [20., 21., 22., 23.]])
>>> a[5, 2]=np.NaN
>>> a.argmax()
22
>>> a.argmin()
22
>>> a.nanargmax()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'nanargmax'

Also, why are the indices "flattened"? Is there a way to have it return indices in the row x column format?

Sorry for the stupid questions!

Thank you,

Mrinmayi


Solution

  • There are many functions in numpy which are available through the module but not as a method on ndarray - this is one of them. You can call nanargmax on an ndarray like this:

    import numpy as np
    a=np.arange(24).reshape(6,4).astype('float')
    print(np.nanargmax(a))