Sub topic 7
Reductions and the axis argument
This chapter assumes you can create arrays, read shape and ndim, and apply elementwise operations such as a + 1 or np.sqrt(a). It covers how reductions collapse an array along a chosen axis and how to predict the result shape.
What a reduction does
A reduction combines many values into fewer values. sum, mean, min, max, prod, std, any and all are common reductions. An elementwise operation keeps the shape. A reduction removes one or more dimensions.
Called with no axis, a reduction combines every element into a single scalar. The axis argument chooses which dimension to collapse instead.
The axis argument
The axis you pass is the one that disappears from the shape. The other axes remain.
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
print(x.sum()) # 21.0
print(x.sum(axis=0)) # [5. 7. 9.]
print(x.sum(axis=1)) # [ 6. 15.]The array has shape (2, 3). Each call gives a different result shape:
x.sum()returns a scalar.x.sum(axis=0)collapses the first axis, so the rows are added together. The result has shape(3,), one total per column.x.sum(axis=1)collapses the second axis, so each row is added across its columns. The result has shape(2,), one total per row.
Why "down the rows" confuses people
For axis 0, people often picture the result as "row-wise". It is easier to think of the index that changes. In x.sum(axis=0), the first index runs over all its values while the second index is held fixed, so you get one total for each column. In x.sum(axis=1), the second index runs while the first is held fixed, so you get one total for each row.
Higher dimensions and negative axes
The same rule works for any number of dimensions. For an array of shape (4, 5, 6), sum(axis=1) gives shape (4, 6). Negative values count from the end, so axis=-1 always means the last axis. This is useful when you do not know how many leading dimensions the array has.
You can also pass a tuple to reduce several axes at once. For shape (4, 5, 6), sum(axis=(0, 2)) gives shape (5,).
Keeping the reduced axis
By default the reduced axis is dropped. Passing keepdims=True keeps it with size 1. The result then has the same number of dimensions as the input.
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
m = x.mean(axis=1, keepdims=True)
print(m.shape) # (2, 1)
print(x - m)
# [[-1. 0. 1.]
# [-1. 0. 1.]]Without keepdims, x.mean(axis=1) has shape (2,). Subtracting it from a (2, 3) array would fail, because NumPy lines shapes up from the right. The (2, 1) shape broadcasts cleanly. Later chapters on broadcasting cover this in detail.
Related reductions
Some functions reduce while reporting something other than a value:
| Function | Result along the axis |
|---|---|
| `argmax`, `argmin` | The index of the largest or smallest value |
| `cumsum`, `cumprod` | A running total. The shape is unchanged |
| `any`, `all` | A boolean for each remaining position |
cumsum accepts axis too, but it does not remove the axis. It is an accumulation, not a reduction.
Common mistakes
- Choosing the wrong axis. Check the result shape with
.shapebefore using the result. - Forgetting that integer input can produce a large integer sum. Pass
dtype=np.float64if you need floating-point accumulation. - Dropping the axis when you need to broadcast the result back. Use
keepdims=True.
Exercise
An array a has shape (4, 5, 6). What is the shape of a.sum(axis=1), and what is the shape of a.mean(axis=(0, 2), keepdims=True)?
Show answer
a.sum(axis=1) removes the axis of size 5, so the shape is (4, 6). a.mean(axis=(0, 2), keepdims=True) reduces axes 0 and 2 but keeps them with size 1, so the shape is (1, 5, 1).
Exercise
For x = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), write an expression that gives the largest value in each column, and state its result.
Show answer
x.max(axis=0) gives [4. 5. 6.]. Axis 0 is collapsed, so each column is reduced to its maximum.