Sub topic 9
Finding where the maximum or minimum is
max and min tell you the largest and smallest values. Often you need to know where those values are: which column has the highest score, or which day had the lowest temperature. NumPy answers this with argmax and argmin, which return positions instead of values.
This chapter assumes you know the axis rules for sum, max and min from earlier chapters. You should also be comfortable with array shapes and with indexing a two-dimensional array as a[row, col].
What argmax and argmin return
argmax returns the index of the largest value. argmin returns the index of the smallest. Like the other reductions, they take an axis argument.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.argmax()) # 5
print(a.argmin()) # 0
print(a.argmax(axis=0)) # [1 1 1]
print(a.argmax(axis=1)) # [2 2]With no axis, NumPy flattens the array in row-major order and returns a position in that flat sequence. Here the maximum 6 is the sixth element, so the answer is 5. The result is not a row and column pair.
With axis=0, each column is searched from top to bottom. In every column the larger value sits in row 1, so the result is [1 1 1]. With axis=1, each row is searched from left to right. In both rows the largest value sits in column 2, so the result is [2 2].
The returned numbers are positions along the axis you searched. They are not positions in the original array. This is the most common source of confusion, and the pitfalls section below returns to it.
The result shape
The searched axis disappears, exactly as it does for sum.
| Call on a `(2, 3)` array | Result shape | Meaning of each entry |
|---|---|---|
| `a.argmax()` | scalar | Position in the flattened array |
| `a.argmax(axis=0)` | `(3,)` | Row index of the maximum in each column |
| `a.argmax(axis=1)` | `(2,)` | Column index of the maximum in each row |
For axis=0 you get one answer per column, and each answer is a row number. For axis=1 you get one answer per row, and each answer is a column number. If you can name what the entries are, you can usually avoid mixing up the two.
Ties: the first occurrence wins
When the extreme value appears more than once, NumPy returns the index of its first occurrence along the searched axis.
import numpy as np
s = np.array([[7, 9, 9],
[3, 3, 1]])
print(s.argmax(axis=1)) # [1 0]
print(s.argmin(axis=1)) # [0 2]Row 0 holds 9 at positions 1 and 2, and the result is 1. Row 1 holds 3 at positions 0 and 1, and the result is 0. NumPy gives you no built-in way to get all tied positions from argmax. If you need them, compare against the maximum:
import numpy as np
s = np.array([[7, 9, 9],
[3, 3, 1]])
is_max = s == s.max(axis=1, keepdims=True)
print(is_max)
# [[False True True]
# [ True True False]]Here keepdims=True lets the row maxima broadcast against s, the same technique used for normalizing and centering.
From a flat index to row and column
For a single answer over the whole array, argmax() gives a flat index. np.unravel_index converts it back to coordinates, given the array's shape.
import numpy as np
m = np.array([[3, 8, 1],
[9, 2, 7]])
flat = m.argmax()
print(flat) # 3
row, col = np.unravel_index(flat, m.shape)
print(row, col) # 1 0
print(m[row, col]) # 9The flattened array is [3, 8, 1, 9, 2, 7], and 9 is at flat position 3. With 3 columns per row, position 3 is row 1, column 0. The same approach works for arrays of any number of dimensions, because unravel_index returns one coordinate per axis.
Getting the values at the argmax positions
An array of indices from argmax(axis=...) can look like it ought to work as m[idx], but it does not. Indexing with m[idx] selects whole rows, not elements. You need one index per axis.
The explicit way is to pair the indices with a range over the other axis:
import numpy as np
m = np.array([[3, 8, 1],
[9, 2, 7]])
idx_rows = m.argmax(axis=1) # column of the max in each row
print(idx_rows) # [1 0]
print(m[np.arange(m.shape[0]), idx_rows]) # [8 9]
idx_cols = m.argmax(axis=0) # row of the max in each column
print(idx_cols) # [1 0 1]
print(m[idx_cols, np.arange(m.shape[1])]) # [9 8 7]For axis=1, the pairs are (0, 1) and (1, 0), which select 8 and 9. For axis=0, the pairs are (1, 0), (0, 1) and (1, 2), which select 9, 8 and 7. These results equal m.max(axis=1) and m.max(axis=0). If you only need the values, call max. This pairing is useful when you need both the values and their positions, or when you use the positions on a different array.
take_along_axis and keepdims
np.take_along_axis removes the need to build the arange by hand, and it works for any number of dimensions. It expects the index array to have the same number of dimensions as the data. In NumPy 1.22 and later, argmax and argmin accept keepdims=True, which produces exactly that shape.
import numpy as np
m = np.array([[3, 8, 1],
[9, 2, 7]])
idx = m.argmax(axis=1, keepdims=True)
print(idx.shape) # (2, 1)
print(np.take_along_axis(m, idx, axis=1))
# [[8]
# [9]]On older NumPy versions, use np.expand_dims(m.argmax(axis=1), axis=1) to get the same index array.
The same index array also picks values from a second array of the same shape. For example, if m holds scores and names holds labels laid out the same way, np.take_along_axis(names, idx, axis=1) returns the label of each row's best score.
Higher dimensions
The searched axis is removed from the shape, as with other reductions.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b.argmax(axis=0).shape) # (3, 4)
print(b.argmax(axis=2).shape) # (2, 3)
print(b.argmax(axis=2))
# [[3 3 3]
# [3 3 3]]Because arange increases along the last axis, the maximum in each 4-element group is always at position 3.
Unlike sum, argmax and argmin accept only one integer axis or None. A tuple such as axis=(0, 2) raises an error, because a single index cannot describe a position across two axes. To search over several axes, either call argmax() on the whole array and use np.unravel_index, or reshape so that the axes you want to combine become one.
Missing values
argmax treats NaN as larger than any number, so it returns the position of the first NaN in a slice that contains one. argmin does the same. NaN is not ignored. np.nanargmax and np.nanargmin skip missing values instead.
import numpy as np
c = np.array([[1.0, np.nan, 5.0],
[6.0, 4.0, 3.0]])
print(c.argmax(axis=1)) # [1 0]
print(np.nanargmax(c, axis=1)) # [2 0]
print(np.nanargmin(c, axis=1)) # [0 2]
try:
np.nanargmax(np.array([[np.nan, np.nan]]), axis=1)
except ValueError as err:
print("ValueError:", err) # ValueError: All-NaN slice encounteredRow 0 of c contains a NaN, so plain argmax reports its position (1). nanargmax skips it and reports the 5 at position 2. A slice made only of NaN has no valid answer, so nanargmax raises ValueError. Check for all-NaN rows first if your data can contain them, for example with np.isnan(c).all(axis=1).
Common mistakes
- Using the result as a position in the whole array.
a.argmax(axis=0)returns row numbers, one per column. It does not return flat indices. - Reading axis backwards.
axis=0searches down each column and gives one answer per column. If the result has the wrong length, you probably chose the other axis. Checkresult.shapeagainst what you expected. - Indexing with
m[idx]. This selects whole rows. Usem[np.arange(n), idx]ornp.take_along_axis. - Expecting all ties. Only the first occurrence is returned.
- Passing a tuple of axes. This is not supported. Reshape or use
unravel_index. - Ignoring NaN. Plain
argmaxcan silently point at a missing value.
Exercise
The array t = np.array([[12, 15, 9], [20, 8, 17], [11, 19, 14]]) holds temperatures. Rows are days and columns are cities. Write code that prints the index of the hottest city on each day, then the day on which each city was coldest, then the (day, city) coordinates of the single hottest reading.
Show answer
print(t.argmax(axis=1)) gives [1 0 1], one city index per day. print(t.argmin(axis=0)) gives [2 1 0], one day index per city. For the hottest reading, use day, city = np.unravel_index(t.argmax(), t.shape), which gives 1 0 because 20 is on day 1 in city 0. In the first two answers the searched axis disappears, so each result has shape (3,).
Exercise
A score array s = np.array([[5.0, np.nan, 7.0], [2.0, 9.0, 4.0]]) has one missing value. What do s.argmax(axis=1) and np.nanargmax(s, axis=1) return, and why do they differ? How would you fetch the best score of each row as a column of shape (2, 1) using nanargmax?
Show answer
s.argmax(axis=1) returns [1 1] because NaN counts as larger than any number, so row 0 points at the NaN. np.nanargmax(s, axis=1) returns [2 1] because it skips the NaN and finds 7.0 at position 2. To get the values as a column, build an index array with idx = np.nanargmax(s, axis=1)[:, np.newaxis], then call np.take_along_axis(s, idx, axis=1), which returns [[7.], [9.]].