The argmin() method returns the index of the smallest element of an array.
Note: In case of more than one occurrence of the smallest element, the index of the first occurrence is returned.
argmin() Syntax
The syntax of argmin() is:
numpy.argmin(array, axis = None, out = None, keepdims = <no value>)
argmin() Arguments
The argmin() 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)
argmin() Return Value
The argmin() method returns the index of the smallest element.
Example 1: argmin() With String
The argmin() method with an array of string or char returns the index of the smallest element based on ASCII value.
Output
0
Example 2: argmin() With 2D Array
The axis argument defines how to handle the index of the smallest 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 smallest element in each column is returned. - If
axis= 1, the index of the smallest element in each row is returned.
Output
Index of the smallest element in the flattened array: 0 Index of the smallest element in each column (axis 0): [0 1 1] Index of the smallest element in each row (axis 1): [0 1]
Example 3: argmin() With 'out' Array
In our previous examples, the argmin() function generated a new array as output.
However, we can use an existing array to store the output using the out argument.
Output
[0 1 2]
Example 4: argmin() 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: [0 1] Shape of array: (2,) With keepdims: [[0] [1]] 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 smallest element in that column.