Python:NumPy argmin()
The ndarray.argmin() method returns the index of the minimum value in a NumPy array. The search can be performed on the flattened array or along a specified axis, and the result reflects where the smallest element appears rather than the value itself.
Syntax
ndarray.argmin(axis=None, out=None, *, keepdims=False)
Parameters:
axis(optional): Axis along which to find the minimum index.None(default): Searches the entire flattened array.0: Searches column-wise1: Searches row-wise
out(optional): Output array that receives the result. Must have the appropriate shape.keepdims(optional): IfTrue, the reduced axes are kept with size 1, preserving the dimension structure.
Return value:
An integer or array of integers representing the indices of the minimum values.
Example 1: Finding the Minimum Index in a 1D Array
In this example, the smallest number in the array is identified, and its index is returned:
import numpy as nparr = np.array([12, 5, 7, 3, 9])idx = arr.argmin()print(idx)
The output of this code is:
3
Example 2: Finding Minimum Indices Along Rows
In this example, argmin() is applied along axis=1, so each row returns the index of its smallest element:
import numpy as nparr = np.array([[4, 9, 1],[8, 3, 6]])idx = arr.argmin(axis=1)print(idx)
The output of this code is:
[2 1]
Codebyte Example
In this example, the minimum index is found both in the flattened array and along each column to show how the output changes with the axis parameter:
Frequently Asked Questions
1. What does NumPy argmin() do?
NumPy’s argmin() returns the index location of the smallest element inside an array. Instead of giving the minimum value, it identifies where that value appears, which is essential for position-based analysis.
2. What is the difference between argmin() and nanargmin()?
argmin() considers all values, including NaNs, while nanargmin() ignores NaNs and returns the index of the smallest non-NaN value.
3. What is the difference between argmin() and min() in Python?
min() (or ndarray.min()) returns the smallest value itself, while argmin() returns the index where that value occurs. One answers “what is the smallest value”, and the other answers “where is that smallest value located”.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours