NumPy Tutorial NumPy Statistics NumPy References

NumPy - argmax() function



The NumPy argmax() function returns the indices of the maximum values along an axis. It is calculated over the flattened array by default, otherwise over the specified axis.

Syntax

numpy.argmax(a, axis=None, out=None)

Parameters

a Required. Specify the input array (array_like).
axis Optional. Specify axis or axes along which the indices of the maximum values are computed. The default is to compute it over the flattened array.
out Optional. Specify output array for the result. The default is None. If provided, it must have the same shape as output.

Return Value

Returns an array containing indices of the maximum values when out=None, otherwise returns a reference to the output array.

Example:

In the example below, argmax() function is used to find out index of the maximum value in the whole array.

import numpy as np
Arr = np.arange(12).reshape(3,4)

print("Array is:")
print(Arr)

#index of maximum value
idx = np.argmax(Arr)
print("\nIndex of maximum value is:", idx)

The output of the above code will be:

Array is:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Index of maximum value is: 11

Example:

When axis parameter is provided, index of maximum value can be calculated over the specified axes. Consider the following example.

import numpy as np
Arr = np.arange(12).reshape(3,4)

print("Array is:")
print(Arr)

#Index of maximum value along axis=0
print("\nIndex of maximum value along axis=0")
print(np.argmax(Arr, axis=0))

#Index of maximum value along axis=1
print("\nIndex of maximum value along axis=1")
print(np.argmax(Arr, axis=1))

The output of the above code will be:

Array is:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Index of maximum value along axis=0
[2 2 2 2]

Index of maximum value along axis=1
[3 3 3]

Example:

When the array contains more than one maximum value, the function returns index of first occurrence of it.

import numpy as np
Arr = [10, 20, 50, 20, 30, 50, 50]

print("Array is:", Arr)

#Index of maximum value
print("Index of maximum value is:", np.argmax(Arr))

The output of the above code will be:

Array is: [10, 20, 50, 20, 30, 50, 50]
Index of maximum value is: 2

❮ NumPy - Functions