The argmax() method returns the index of the largest element of an array.
Note: In case of more than one occurrence of the largest element, the index of the first occurrence is returned.
argmax() Syntax
The syntax of argmax() is:
numpy.argmax(array, axis = None, out = None, keepdims = <no value>)
argmax() Arguments
The argmax() method takes four arguments:
array- input arrayaxis(optional) - axis along which index is returned (int)out(optional) - array to store the outputkeepdims(optional) - whether to preserve the input array's dimension (bool)
argmax() Return Value
The argmax() method returns the index of the largest element.
Example 1: argmax() With String
The argmax() method with an array of string or char returns the index of the largest element based on ASCII value.
Output
2
Example 2: argmax() With 2D Array
The axis argument defines how we can handle the index of the largest element in a 2D array.
- If
axis=None, the array is flattened and the index of the flattened array is returned. - If
axis= 0, the index of the largest element in each column is returned. - If
axis= 1, the index of the largest element in each row is returned.
Output
Index of the largest element in the flattened array: 2 Index of the largest element in each row (axis 0): [1 0 0] Index of the largest element in each row (axis 1): [2 2]
Example 3: argmax() With 'out' Array
In our previous examples, the argmax() function generated a new array as output.
However, we can use an existing array to store the output using the out argument.
Output
[1 2 0]
Example 4: argmax() With keepdims
When keepdims = True, the dimensions of the resulting array matches the dimension of an input array.
Output
Shape of original array: (2, 3) Without keepdims: [2 2] Shape of array: (2,) With keepdims: [[2] [2]] Shape of array: (2, 1)
Without keepdims, the result is simply a one-dimensional array of indices.
With keepdims, the resulting array has the same number of dimensions as the input array.
Similarly, with axis = 1 and keepdims = True, the resulting array has the same number of rows as the input array, but its columns have a single element i.e. the index of the largest element in that column.