The np.argmin() is a numpy library method that returns the index of the minimum value in a given array. If the input array has multiple dimensions, the function will treat it as a flattened array unless the axis parameter is specified. In the case of multiple occurrences of the minimum value, the index of the first occurrence will be returned.
Syntax
numpy.argmin(arr,axis=None,out=None)
Parameters
The numpy argmin() function takes three arguments:
- arr: The array from which we want the indices of the min element.
- axis: By default, it is None. But for the multidimensional array, if we find an index of any maximum of element row-wise or column-wise, we have to give axis=1 or axis=0, respectively.
- out: If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.
Return Value
The np.argmin() function returns an array containing the indices of the minimum elements.
Example 1
#Importing numpy
import numpy as np
#We will create an 1D array
arr = np.array([4, 24, 63, 121, 4, 64])
#Printing the array
print("The array is: ", arr)
#Shape of the array
print("Shape of the array is : ", np.shape(arr))
#Now we will print index of min value of this array
print("Index of minimum value of the given array is: ", np.argmin(arr))
Output
The array is: [ 4 24 63 121 4 64]
Shape of the array is : (6,)
Index of minimum value of the given array is: 0
In this program, we have first declared an array with some
random numbers given by the user. Then we printed the shape (size) of the array. Then we called argmin() to get the index of the minimum element from the array. We can see that the minimum element of this array is 4, which is at position 0, so the output is 0.
Example 2
#Importing numpy
import numpy as np
#We will create a 2D array
#Of shape 4x3
arr = np.array([(1, 9, 4), (6, 55, 4), (1, 3, 40), (5, 6, 4)])
#Printing the array
print("The array is: ")
print(arr)
print("Shape of the array is: ", np.shape(arr))
#Now we will find the indices of minimum value for some cases
#Indices of minimum value of each row
a = np.argmin(arr, axis=1)
print("Indices of minimum value of each row of the array is: ", a)
#Indices of minimum value of each column
b = np.argmin(arr, axis=0)
print("Indices of minimum value of each column of the array is: ", b)
Output
The array is:
[[ 1 9 4]
[ 6 55 4]
[ 1 3 40]
[ 5 6 4]]
Shape of the array is: (4, 3)
Indices of minimum value of each row of the array is: [0 2 0 2]
Indices of minimum value of each column of the array is: [0 2 0]
In this program, we have first declared a matrix of size 4×3; you can see the shape of the matrix also, which is (4,3). Then we called argmin() to get the output of different cases.
That’s it.