NumPy ndarray.argmin()
The numpy.ndarray.argmin()
method returns the index of the minimum value in a NumPy array.
It can operate across the entire array or along a specified axis.
Syntax
ndarray.argmin(axis=None, out=None, *, keepdims=False)
Parameters
Parameter | Type | Description |
---|---|---|
axis | None, int, or tuple of ints, optional | Axis along which to find the index of the minimum value. If None , the index is for the flattened array. |
out | ndarray, optional | Alternative output array for storing the result. Must have the same shape as the expected output. |
keepdims | bool, optional | If True , the reduced dimensions are kept as size one, allowing proper broadcasting. |
Return Value
Returns an integer index if axis=None
, or an array of indices if an axis is specified.
The result represents the position of the first occurrence of the minimum value.
Examples
1. Finding the Index of the Minimum Element
In this example, we create a 1D array and find the index of the minimum value.
import numpy as np
arr = np.array([4, 2, 1, 7, 5])
index = arr.argmin()
print(index)
Output:
2
The minimum value in the array is 1
, which is at index 2
.
2. Using the axis
Parameter in ndarray.argmin()
Here, we find the index of the minimum value along a specific axis.
import numpy as np
arr = np.array([[3, 1, 4],
[2, 8, 5]])
index_axis0 = arr.argmin(axis=0)
print(index_axis0)
index_axis1 = arr.argmin(axis=1)
print(index_axis1)
Output:
[1 0 0]
[1 0]
For axis=0
(columns), the indices correspond to the row positions of the minimum values in each column.
For axis=1
(rows), the indices correspond to the column positions of the minimum values in each row.
3. Keeping Dimensions with keepdims=True
in ndarray.argmin()
In this example, we use keepdims=True
to retain the reduced axis as a dimension of size one.
import numpy as np
arr = np.array([[3, 1, 4],
[2, 8, 5]])
index = arr.argmin(axis=1, keepdims=True)
print(index)
Output:
[[1]
[0]]
By setting keepdims=True
, the result retains the original number of dimensions, making it useful for broadcasting.