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 already know sum, mean, max, and keepdims. It collects the errors people make most often with axis. Some of these errors raise an exception. The dangerous ones return a wrong answer with no warning, so the chapter also gives you habits for catching them.
The one rule behind most mistakes
The axis you name is the axis that disappears from the shape. For an array of shape (3, 4):
axis=0removes the first dimension and leaves shape(4,). This is one value per column.axis=1removes the second dimension and leaves shape(3,). This is one value per row.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a.sum(axis=0), a.sum(axis=0).shape) # [12 15 18 21] (4,)
print(a.sum(axis=1), a.sum(axis=1).shape) # [ 6 22 38] (3,)A common slip is to read axis=0 as "sum the rows" and expect three values. The result shape tells you which reading is correct. Work out the expected shape before you run the code, and compare it with the actual shape afterwards.
Mistake 1: Dividing by a reduced result without keepdims
This is the most damaging mistake because a square array hides it. Suppose you want each row to sum to 1.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
wrong = a / a.sum(axis=1) # shape (3, 3) / (3,)
right = a / a.sum(axis=1, keepdims=True) # shape (3, 3) / (3, 1)
print(np.round(wrong[0], 3)) # [0.167 0.133 0.125]
print(np.allclose(wrong.sum(axis=1), 1)) # False
print(np.allclose(right.sum(axis=1), 1)) # Truea.sum(axis=1) has shape (3,). Broadcasting aligns shapes from the right, so that vector is stretched along the rows. Element [i, j] is divided by the total of row j, not row i. The shapes are compatible, so NumPy raises no error.
With a non-square array the same code fails loudly:
import numpy as np
b = np.arange(1, 7).reshape(2, 3)
try:
b / b.sum(axis=1) # shapes (2, 3) and (2,)
except ValueError:
print("broadcast error") # the shapes do not line upThe error is the lucky case. Test your code on non-square arrays so that this mistake shows up as an error.
Mistake 2: Axis out of range and negative axes
Naming an axis that does not exist raises an AxisError. This error is a subclass of ValueError, so except ValueError catches it.
import numpy as np
a = np.arange(6).reshape(2, 3)
try:
a.sum(axis=2) # a has only axes 0 and 1
except ValueError as err:
print("bad axis:", err)
print(a.sum(axis=-1)) # [ 3 12]
print(a.sum(axis=-2)) # [3 5 7]Negative values count from the end, so axis=-1 is the last axis. Use -1 when you mean "the last axis, whatever the number of dimensions". This helps in code that must handle both 2-D and 3-D input. The code is then correct for any dimension count, but you must still know what the last axis represents. For example, an image array of shape (height, width, channels) has color channels on axis -1.
Mistake 3: Forgetting that `axis=None` flattens
Without an axis, the reductions treat the array as one flat sequence. For sum, max, and mean this gives a single number, which is usually what you want. Two functions behave in ways that surprise people.
cumsum does not collapse its result, so with no axis it returns a flattened 1-D array:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.cumsum(a)) # [ 1 3 6 10 15 21] (shape (6,))
print(np.cumsum(a, axis=1)) # per-row running totals, shape (2, 3)argmax and argmin return an index into the flattened array:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
flat = a.argmax()
print(flat) # 5
row, col = np.unravel_index(flat, a.shape)
print(row, col) # 1 2np.unravel_index converts a flat index back to row and column positions. Pass an explicit axis when you want one position per row or per column.
Mistake 4: Confusing a reduction with a cumulative function
A reduction removes the axis from the shape. A cumulative function keeps it. If a line of code is supposed to return one value per row and you get a full-size array back, check whether you called cumsum or cumprod instead of sum or prod. The reverse mistake is also common. Calling sum when you wanted running totals gives you a smaller array than the one you passed in.
Mistake 5: Letting NaN or small integer types change the answer
NaN values propagate through ordinary reductions, so one missing value turns a whole row or column into nan. The nan-prefixed functions skip them. An all-NaN slice behaves differently by function. np.nansum returns 0 for it, and np.nanmean returns nan with a RuntimeWarning. Decide in advance what an empty column should mean for your analysis.
Integer width matters only when you override it. By default sum on small integer types is computed in a larger integer type, but an explicit dtype wraps around silently:
import numpy as np
x = np.array([100, 100], dtype=np.int8)
print(x.sum()) # 200
print(x.sum(dtype=np.int8)) # -56 (200 wraps around in 8 bits)Overflow in integer arithmetic produces no warning, so a wrong total looks like any other number.
A symptom-to-cause table
| Symptom | Likely cause | Check or fix |
|---|---|---|
| Result has the wrong length | Axis reversed | Compare `result.shape` with the shape you predicted |
| Normalized rows do not sum to 1 | Missing `keepdims=True` on a square array | Reduce with `keepdims=True` and check `np.allclose(out.sum(axis=1), 1)` |
| `ValueError` about broadcasting | Reduced vector has shape `(n,)` where `(n, 1)` is needed | Add `keepdims=True` |
| `AxisError` | Axis number is at least `ndim` | Print `a.ndim`, or use a negative axis |
| `cumsum` returns a 1-D array | No `axis` was given | Pass `axis=` explicitly |
| `argmax` returns one number | No `axis` was given | Pass `axis=`, or use `np.unravel_index` |
| Whole column is `nan` | NaN propagated | Use `np.nansum` or `np.nanmean` |
A debugging routine
Use the same steps whenever an aggregation looks wrong.
You can automate the first check. The helper below computes the shape a reduction should produce, and handles single axes, tuples of axes, and negative axes.
import numpy as np
def expected_shape(shape, axis):
axes = (axis,) if isinstance(axis, int) else tuple(axis)
axes = {ax % len(shape) for ax in axes}
return tuple(n for i, n in enumerate(shape) if i not in axes)
probe = np.zeros((2, 3, 4))
for axis in (0, 1, -1, (0, 2)):
actual = probe.sum(axis=axis).shape
assert actual == expected_shape(probe.shape, axis), axis
print(axis, "->", actual)
# 0 -> (3, 4)
# 1 -> (2, 4)
# -1 -> (2, 3)
# (0, 2) -> (3,)The probe array has three different dimension lengths, so any axis mixup produces a visibly different shape. The same trick works on real data. Build a small zero array with the same number of dimensions and different lengths, and run your aggregation on it before trusting the code on the full dataset.
Summary of habits
- Predict the result shape first: the input shape with the named axes removed.
- Use
keepdims=Truewhenever the result will be combined with the original array. - Test on arrays whose dimensions all differ.
- Pass
axisexplicitly tocumsum,argmax, andargmin. - Treat NaN handling and
dtypeas part of the aggregation, not as an afterthought.
Exercise
A colleague writes centered = data - data.mean(axis=0) for an array data of shape (5, 5) and says it centers each row. Is that correct? What does the line do, and how would you center each row instead?
Show answer
It is not correct. axis=0 produces one mean per column, with shape (5,). That vector broadcasts across the rows, so the code subtracts each column's mean from that column and centers the columns. To center each row, compute data - data.mean(axis=1, keepdims=True). The keepdims=True gives the means shape (5, 1), so each row mean is subtracted from its own row. Without it, the (5,) vector would broadcast along the rows and subtract the wrong values, with no error because the array is square.
Exercise
For b = np.arange(24).reshape(2, 3, 4), what are the shapes of b.sum(axis=1), b.sum(axis=-1), and b.sum(axis=(0, 1))? Which call would raise an AxisError, b.sum(axis=3) or b.sum(axis=-3)?
Show answer
The shapes are (2, 4), (2, 3), and (4,). Each result is the input shape (2, 3, 4) with the named axes removed. b.sum(axis=3) raises an AxisError, because the valid axes are 0, 1, 2 and their negative equivalents -3, -2, -1. b.sum(axis=-3) is valid and is the same as axis=0.