Module 4 · Lesson 2

argmin/argmax and Locating Extremes

.max() tells you the value; .argmax() tells you where it is. Called on a flat array, argmax returns a single flat index. Called with axis on a 2-D array, it returns one index per row/column — the position within that row/column, not a flat index into the whole array.

To turn a flat index (from calling argmax() on a 2-D array with no axis) back into (row, col) coordinates, use np.unravel_index(flat_index, arr.shape).

grid = np.array([[3, 9, 1],
                  [7, 2, 8]])

print("flat argmax:", grid.argmax())                 # index into flattened array
print("as coords:  ", np.unravel_index(grid.argmax(), grid.shape))
print("argmax per row (axis=1):", grid.argmax(axis=1))
print("argmin per column (axis=0):", grid.argmin(axis=0))

Output:

flat argmax: 1
as coords:   (np.int64(0), np.int64(1))
argmax per row (axis=1): [1 2]
argmin per column (axis=0): [0 1 0]
2.1

Find the hotspot

Write hotspot(grid) that returns the (row, col) coordinates (as a tuple of two Python ints) of the single largest value in a 2-D array.

💡 Hint

np.unravel_index(grid.argmax(), grid.shape) gives you the coordinates as numpy integers — wrap each in int(...) for plain Python ints.

✅ Solution
def hotspot(grid):
    row, col = np.unravel_index(grid.argmax(), grid.shape)
    return (int(row), int(col))
2.2

Best score per student

Each row of scores is one student's scores across several tests. Write best_test_per_student(scores) that returns a 1-D array with, for each student (row), the index (0-based, position within that row) of their best test.

💡 Hint

You want one argmax per row — that's axis=1.

✅ Solution
def best_test_per_student(scores):
    return scores.argmax(axis=1)