Finding index of maximum value in array with NumPy

arrays, max, numpy, python

Solution

Numpy has an `argmax` function that returns just that, although you will have to deal with the `nan`s manually. `nan`s always get sorted to the end of an array, so with that in mind you can do:

a = np.random.rand(10000)
a[np.random.randint(10000, size=(10,))] = np.nan
a = a.reshape(100, 100)

def nanargmax(a):
    idx = np.argmax(a, axis=None)
    multi_idx = np.unravel_index(idx, a.shape)
    if np.isnan(a[multi_idx]):
        nan_count = np.sum(np.isnan(a))
        # In numpy < 1.8 use idx = np.argsort(a, axis=None)[-nan_count-1]
        idx = np.argpartition(a, -nan_count-1, axis=None)[-nan_count-1]
        multi_idx = np.unravel_index(idx, a.shape)
    return multi_idx

>>> nanargmax(a)
(20, 93)

Problem

I would like to find a maximum in a `float64` array, excluding `nan` values. I saw `np.nanmax` function but it doesn't give the index corresponding to the found value. it 's quite strange to scan after to the value specially the function necessarily use the index ??? Can't it be a mistake searching like that . isn't there a way to recover the index directly ?

Original source