Search code examples
pythonarraysnumpymaxargmax

Python: how to interpret the outcome of np.argmax()?


The documentation on np.argmax() says that it

Returns the indices of the maximum values along an axis.

The examples given are straightforward:

In[1]: a = np.arange(6).reshape(2,3)
In[2]: a
Out[2]: array([[0, 1, 2],
       [3, 4, 5]])

In[3]: np.argmax(a)
Out[3]: 5

In[4]: np.argmax(a, axis=0)
Out[4]: array([1, 1, 1]) 

In[5]: np.argmax(a, axis=1)
Out[5]: array([2, 2])

Except in the case of

 In[4]: np.argmax(a, axis=0)
 Out[4]: array([1, 1, 1])

Since 5 corresponds to a[1][2], why is it returning array([1, 1, 1])?

Also, if I assign

In[6]: b=np.array([[[2,3,4],[4,5,6]],[[3,7,1],[2,5,9]]])
In[7]: b
Out[7]: array([[[2, 3, 4],
        [4, 5, 6]],
       [[3, 7, 1],
        [2, 5, 9]]])

and then ask for the maximum value, why do these two return a different value?

In[8]: b.max()
Out[8]: 9

In[9]: np.argmax(b)
Out[9]: 11

Why does np.argmax() return the integer 11, when that number does not even appear in the array?


Solution

  • Function np.argmax() returns the index of the maximum value, not the value.

    In case of array a, each row in array a (you are asking per row, by specifying axis=0) has its maximum at index 1, namely 3, 4, and 5. The three rows are [0, 3], [1, 4], and [2, 5]. In case you asked the argmin(), it would have returned array([0, 0, 0]).

    The value of 9 is the element at index 11 of the flattened array b.