How to Use argmin and argmax in NumPy for Finding Indexes
numpy.argmin() to find the index of the smallest value and numpy.argmax() to find the index of the largest value in a NumPy array. Both functions return the position of these values, which helps locate them quickly in data.Syntax
numpy.argmin(a, axis=None, out=None) returns the index of the minimum value in the array a. If axis is specified, it returns indices along that axis.
numpy.argmax(a, axis=None, out=None) works similarly but returns the index of the maximum value.
- a: Input array to search.
- axis: Axis along which to find the index. Default is None (flattened array).
- out: Optional output array to store results.
numpy.argmin(a, axis=None, out=None) numpy.argmax(a, axis=None, out=None)
Example
This example shows how to find the index of the smallest and largest values in a 1D and 2D NumPy array.
import numpy as np # 1D array example arr1d = np.array([4, 2, 7, 1, 9]) min_index_1d = np.argmin(arr1d) max_index_1d = np.argmax(arr1d) # 2D array example arr2d = np.array([[3, 8, 5], [7, 1, 6]]) min_index_2d_axis0 = np.argmin(arr2d, axis=0) # min indices for each column max_index_2d_axis1 = np.argmax(arr2d, axis=1) # max indices for each row print(f"1D array: {arr1d}") print(f"Index of min value: {min_index_1d}") print(f"Index of max value: {max_index_1d}") print(f"\n2D array:\n{arr2d}") print(f"Index of min values along axis 0 (columns): {min_index_2d_axis0}") print(f"Index of max values along axis 1 (rows): {max_index_2d_axis1}")
Common Pitfalls
One common mistake is forgetting that argmin and argmax return the index, not the value itself. To get the value, you must use the index on the array.
Another pitfall is misunderstanding the axis parameter. If you don't specify axis, the array is flattened, and the index is relative to the flattened array, which can be confusing for multi-dimensional arrays.
import numpy as np arr = np.array([[10, 20], [30, 5]]) # Wrong: expecting value, but gets index min_val_wrong = np.argmin(arr) # Right: get index, then value min_index = np.argmin(arr) min_val_right = arr.flat[min_index] # Axis confusion example min_index_axis0 = np.argmin(arr, axis=0) # min index per column min_index_axis1 = np.argmin(arr, axis=1) # min index per row print(f"Wrong (index instead of value): {min_val_wrong}") print(f"Right (value using index): {min_val_right}") print(f"Min indices along axis 0: {min_index_axis0}") print(f"Min indices along axis 1: {min_index_axis1}")
Quick Reference
Remember these quick tips when using argmin and argmax:
- They return the index of the min or max value, not the value itself.
- Use
axisto specify the dimension to search along. - For multi-dimensional arrays, indices correspond to positions along the chosen axis.
- Use the returned index to access the actual value from the array.