0
0
NumPydata~5 mins

np.argmin() and np.argmax() in NumPy

Choose your learning style9 modes available
Introduction

These functions help find the position of the smallest or largest value in data. This is useful to quickly locate important points in your data.

Finding the day with the lowest temperature in a week.
Identifying the highest score in a test among students.
Locating the minimum or maximum sales value in a monthly report.
Determining the index of the fastest runner in a race.
Finding the position of the cheapest product in a price list.
Syntax
NumPy
np.argmin(array, axis=None)
np.argmax(array, axis=None)

array is the data you want to check.

axis lets you choose if you want the position in the whole array or along rows/columns.

Examples
Finds the index of the smallest value in a simple list.
NumPy
np.argmin([3, 1, 2])
Finds the index of the largest value in a simple list.
NumPy
np.argmax([3, 1, 2])
Finds the index of the smallest value in each column.
NumPy
np.argmin([[5, 2, 3], [1, 4, 6]], axis=0)
Finds the index of the largest value in each row.
NumPy
np.argmax([[5, 2, 3], [1, 4, 6]], axis=1)
Sample Program

This program uses np.argmin() and np.argmax() to find positions of lowest and highest scores in a 2D array of student test scores. It shows how to find these positions overall and along rows or columns.

NumPy
import numpy as np

# Create a 2D array representing scores of 3 students in 4 tests
scores = np.array([[88, 92, 79, 93],
                   [85, 90, 91, 89],
                   [90, 85, 88, 92]])

# Find the index of the lowest score overall
lowest_score_index = np.argmin(scores)

# Find the index of the highest score overall
highest_score_index = np.argmax(scores)

# Find the index of the lowest score in each test (column-wise)
lowest_per_test = np.argmin(scores, axis=0)

# Find the index of the highest score for each student (row-wise)
highest_per_student = np.argmax(scores, axis=1)

print(f"Lowest score index overall: {lowest_score_index}")
print(f"Highest score index overall: {highest_score_index}")
print(f"Lowest score index per test (column-wise): {lowest_per_test}")
print(f"Highest score index per student (row-wise): {highest_per_student}")
OutputSuccess
Important Notes

Indexes start at 0, so the first element is at position 0.

If you do not specify axis, the function treats the array as flat (1D).

These functions return the first occurrence if there are multiple equal min or max values.

Summary

np.argmin() finds the position of the smallest value.

np.argmax() finds the position of the largest value.

You can find positions overall or along rows/columns using the axis parameter.