Sub topic 10
Reductions along an axis
This chapter assumes you can create arrays, read their shape, and apply broadcasting rules. A reduction collapses an array to a smaller one by combining elements. sum, mean, max, min, and std are common reductions.
Reducing the whole array
With no axis argument, a reduction combines every element into one scalar.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.sum()) # 21
print(m.max()) # 6Choosing an axis
The axis argument names the dimension that disappears. The result keeps the other dimensions. For a (2, 3) array, axis=0 removes the first dimension and leaves shape (3,). axis=1 removes the second and leaves shape (2,).
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.sum(axis=0)) # [5 7 9], one total per column
print(m.sum(axis=1)) # [ 6 15], one total per rowA useful rule: the result's shape is the original shape with the chosen axis removed. This also works for three or more dimensions. A (4, 5, 6) array reduced with axis=1 gives shape (4, 6).
Keeping dimensions with keepdims
Removing an axis can break later broadcasting. Passing keepdims=True keeps the reduced axis with length 1, so the result still lines up with the original array.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
row_sums = m.sum(axis=1, keepdims=True)
print(row_sums.shape) # (2, 1)
print(m / row_sums) # each row now sums to 1
print(m - m.mean(axis=0)) # subtract each column's meanWithout keepdims, row_sums would have shape (2,). Dividing a (2, 3) array by it would fail, because the trailing dimensions 3 and 2 do not match.
Several axes and other reductions
axis accepts a tuple, which collapses several dimensions at once. Reductions such as argmax return the position of the result instead of its value.
import numpy as np
cube = np.arange(24).reshape(2, 3, 4)
print(cube.sum(axis=(0, 2))) # shape (3,)
m = np.array([[1, 9, 3], [4, 5, 6]])
print(m.argmax(axis=1)) # [1 2], column index of each row's maxCommon errors
- Mixing up the direction.
axis=0does not mean "sum across rows" in the sense of one total per row. It combines values down the rows and gives one result per column. - Forgetting
keepdimsand getting a broadcasting error or a silently wrong result. A(3,)array broadcast against a(3, 3)array aligns with the last axis, which may not be the one you meant. - Using an integer dtype for averages.
meanreturns floats, butsumon small integer types such asint8can overflow. Passdtype=np.int64if needed.
Exercise
A float array scores has shape (4, 3): four students, three tests. Write an expression that subtracts each student's own average from their scores, and state the shape of the intermediate average array.
Show answer
scores - scores.mean(axis=1, keepdims=True). The intermediate array has shape (4, 1), which broadcasts against (4, 3). Without keepdims=True the shape would be (4,), and the subtraction would raise an error because 3 and 4 do not match.