Sub topic 14
Common axis mistakes and how to check them
This chapter assumes you can create arrays with np.array and np.arange, read an array's shape, and use sum, mean, max, and keepdims with an axis argument. It collects the errors that come up most often and gives you quick ways to catch them.
Mistake 1: Reading axis as "the thing that stays"
axis=0 does not mean "keep the rows". It means "collapse axis 0". The length of axis 0 disappears from the result, and the other axes remain.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape) # (2, 3)
print(a.sum(axis=0)) # [5 7 9] -> shape (3,), one value per column
print(a.sum(axis=1)) # [ 6 15] -> shape (2,), one value per rowA reliable check is to remove the axis number from the shape tuple. Removing index 0 from (2, 3) leaves (3,). Removing index 1 leaves (2,).
Mistake 2: Skipping keepdims before broadcasting
A row total has shape (2,). The original array has shape (2, 3). NumPy lines shapes up from the right, so it compares 3 with 2 and fails.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
totals = a.sum(axis=1)
try:
a / totals
except ValueError as e:
print(e)
shares = a / a.sum(axis=1, keepdims=True)
print(shares.sum(axis=1)) # [1. 1.]The first division raises ValueError because (2, 3) and (2,) are not compatible. With keepdims=True the total has shape (2, 1), which broadcasts across the columns.
The danger is a square array. If a is (3, 3), then a / a.sum(axis=1) does not raise an error. It divides each column by the matching row total, and the result is silently wrong.
Mistake 3: Expecting cumulative functions to reduce
sum removes an axis. cumsum keeps the shape and returns a running total.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=1).shape) # (2,)
print(np.cumsum(a, axis=1).shape) # (2, 3)If you call cumsum without axis, NumPy flattens the array first and returns a one-dimensional result. That is rarely what you want for a table of data.
Mistake 4: Confusing argmax with max
max returns a value. argmax returns a position along the chosen axis. Without axis, argmax returns a position in the flattened array, not a pair of row and column indices.
Mistake 5: Letting NaN spread
A single np.nan turns the sum of its column into nan. Use np.nansum or np.nanmean when missing values are expected, and note that these functions skip the missing values instead of reporting them.
A checking routine
- Write down the input shape.
- Remove the axis (or axes) you reduce. That is the expected output shape.
- Assert it in code.
- Test with a small array whose answer you can compute by hand.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
result = b.sum(axis=(0, 2))
expected_shape = (3,)
assert result.shape == expected_shape, result.shape
# Hand check on the first slice along axis 1
manual = b[:, 0, :].sum()
assert result[0] == manual
print(result) # [ 60 92 124]The shape assertion catches wrong axis choices. The hand check catches mistakes that keep the shape correct, such as using the wrong axis on a square array.
Exercise
An array m has shape (4, 4). You write m / m.sum(axis=0) intending to divide each column by its own total. Does it do that? What is the shape of m.sum(axis=0), and how would you make the intent explicit?
Show answer
Yes, in this case it works by accident of the rule, not by design. m.sum(axis=0) has shape (4,), which broadcasts across the rows, so each column is divided by its own column total. That is the correct column normalization. If you wanted to divide each row by its row total, m / m.sum(axis=1) would be wrong without error, because the (4,) result would still broadcast along columns and divide by the wrong values. Use m / m.sum(axis=1, keepdims=True) for rows, and keepdims=True on both for clarity.