Sub topic 6
Keeping the reduced axis with keepdims
This chapter assumes you can create arrays with np.array and np.arange, read an array's shape, and use axis with sum, mean, max, and min. Here you will learn what keepdims=True does to the result's shape and why that matters when you combine a result with the original array.
The problem: the reduced axis disappears
When you reduce along an axis, NumPy removes that axis from the result's shape. For a (2, 3) array, sum(axis=1) returns shape (2,). The row totals are a one-dimensional array with no trace of the axis you collapsed.
That is fine when you only want the numbers. It causes trouble when you want to use the totals in an expression with the original array, because broadcasting lines up shapes from the right.
What keepdims does
Passing keepdims=True keeps the reduced axis in the result with length 1. The number of dimensions stays the same as the input.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=1).shape) # (2,)
print(a.sum(axis=1, keepdims=True).shape) # (2, 1)
print(a.sum(axis=0, keepdims=True).shape) # (1, 3)
print(a.sum(keepdims=True).shape) # (1, 1)The last line shows that even a full reduction with no axis keeps both dimensions, each with length 1.
Why it helps: broadcasting
Broadcasting compares shapes from the last axis backward. A (2, 3) array and a (2, 1) array are compatible, because the length-1 axis stretches to 3. A (2, 3) array and a (2,) array are not, because 3 and 2 do not match.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
row_totals = a.sum(axis=1, keepdims=True)
print(row_totals.shape) # (2, 1)
shares = a / row_totals # each row now sums to 1
print(shares.sum(axis=1)) # [1. 1.]
centered = a - a.mean(axis=0)
print(centered)
# [[-1.5 -1.5 -1.5]
# [ 1.5 1.5 1.5]]Row normalization needs keepdims=True because the totals must line up with the rows. Column centering works without it. a.mean(axis=0) has shape (3,), and that already matches the last axis of a.
The rule of thumb
Use keepdims=True whenever you reduce and then combine the result with the original array. It works for any axis and any number of dimensions, so you do not need to remember which case needs a reshape.
Without keepdims, you would have to restore the axis by hand:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
totals = a.sum(axis=1) # shape (2,)
shares = a / totals[:, np.newaxis] # shape (2, 1) after indexing
print(shares.shape) # (2, 3)This gives the same result, but keepdims=True is shorter and states the intent.
What happens if you forget it
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
try:
a / a.sum(axis=1)
except ValueError as e:
print(e)NumPy raises a ValueError saying the operands could not be broadcast together with shapes (2,3) and (2,). If the array were square, say (3, 3), the same mistake would not raise an error. It would silently divide each column by the matching row total, which gives wrong numbers. Checking .shape after a reduction is a cheap safeguard.
Exercise
Given m = np.arange(12).reshape(3, 4), write an expression that subtracts each row's mean from that row. What is the shape of the intermediate row means, and why does it need that shape?
Show answer
Use m - m.mean(axis=1, keepdims=True). The row means have shape (3, 1). That shape broadcasts against (3, 4) by stretching the length-1 axis to 4. Without keepdims=True the means would have shape (3,), which does not match the last axis of length 4 and raises a ValueError.
Exercise
What is the shape of np.ones((4, 5, 6)).max(axis=(0, 2), keepdims=True)?
Show answer
(1, 5, 1). Both reduced axes stay with length 1, and the axis that was not reduced keeps its length of 5.