Sub topic 10
Reductions along an axis
This chapter assumes you can create arrays, read shape, and know that operations on arrays of different shapes follow the broadcasting rules. You will use all three here.
What a reduction does
A reduction collapses many values into fewer values. sum, mean, max, min, prod, std, var, any, all, argmax, and argmin are reductions. Each exists both as a function (np.sum(a)) and as an array method (a.sum()).
With no axis argument, the reduction flattens the array and returns one scalar. With axis, you choose which dimension to collapse.
The axis rule: the named axis disappears
axis=k means "run along dimension k and combine its values". That dimension is removed from the result shape. All other dimensions stay.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3)
print(m.sum()) # 21, axis=None collapses everything
print(m.sum(axis=0)) # [5 7 9], shape (3,), axis 0 removed
print(m.sum(axis=1)) # [ 6 15], shape (2,), axis 1 removed
print(m.sum(axis=-1)) # [ 6 15], negative axes count from the endA common mistake is reading axis=0 as "sum each row". It sums down the rows, so you get one value per column. Predict the result shape instead of the direction: delete the axis from the shape tuple.
The same rule works in any number of dimensions.
import numpy as np
t = np.arange(24).reshape(2, 3, 4)
print(t.sum(axis=0).shape) # (3, 4)
print(t.sum(axis=1).shape) # (2, 4)
print(t.sum(axis=(0, 2))) # [ 60 92 124], shape (3,)
print(t.sum(axis=1, keepdims=True).shape) # (2, 1, 4)Passing a tuple reduces several axes at once. Here axes 0 and 2 are removed, which leaves one value per index of axis 1.
Common reductions
| Function | Result | Notes |
|---|---|---|
| `sum`, `prod` | Total or product | Integer inputs smaller than the platform integer are widened |
| `mean`, `std`, `var` | Statistics | Always return floats for integer input |
| `min`, `max` | Extreme value | Raise `ValueError` on an empty axis |
| `argmin`, `argmax` | Index of the extreme | Index is along the chosen axis; first occurrence wins on ties |
| `any`, `all` | Boolean | Work on any dtype, where nonzero counts as true |
argmax returns positions, not values, so the result is an integer array.
import numpy as np
scores = np.array([[0.2, 0.7, 0.1],
[0.5, 0.3, 0.2]])
print(scores.argmax(axis=1)) # [1 0], best column for each row
print(scores.max(axis=1)) # [0.7 0.5]Without an axis, argmax returns an index into the flattened array. Use np.unravel_index to convert it back to coordinates.
keepdims and broadcasting
A reduced result has one fewer dimension, so it often cannot broadcast back against the original array. keepdims=True keeps the reduced axis with length 1, and the result then broadcasts correctly.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
row_means = m.mean(axis=1, keepdims=True) # shape (2, 1)
print(m - row_means)
# [[-1. 0. 1.]
# [-1. 0. 1.]]Without keepdims, m.mean(axis=1) has shape (2,). Subtracting it from a (2, 3) array raises a ValueError, because broadcasting aligns shapes from the right and compares 3 with 2.
import numpy as np
s = np.arange(9).reshape(3, 3)
wrong = s / s.sum(axis=1) # no error, wrong result
right = s / s.sum(axis=1, keepdims=True) # each row sums to 1
print(np.allclose(right.sum(axis=1), 1.0)) # True
print(np.allclose(wrong.sum(axis=1), 1.0)) # FalseWhen you normalize or center along an axis, use keepdims=True by default. It makes the intent explicit and works for any shape.
Counting with boolean reductions
A comparison produces a boolean array, and True counts as 1 in a sum. This gives you counts and proportions without loops.
import numpy as np
temps = np.array([[18, 25, 31],
[22, 35, 29]])
hot = temps > 30
print(hot.sum()) # 2 hot readings in total
print(hot.sum(axis=1)) # [1 1] per row
print(hot.mean()) # 0.333..., fraction of hot readings
print(hot.any(axis=0)) # [False True True]
print((temps > 15).all()) # TrueDtype behavior and accumulators
Reductions have rules about the type of the running total, called the accumulator. These rules cause most surprises.
- Integer arrays smaller than the platform integer (such as
int8) are summed in the platform integer by default, so the default does not overflow. - If you pass
dtype=explicitly, the accumulator uses that type and can wrap around. meanof an integer array computes infloat64.meanof afloat32array accumulates infloat32. For large arrays, passdtype=np.float64to reduce rounding error.
import numpy as np
a = np.array([100, 100], dtype=np.int8)
print(a.sum()) # 200, widened automatically
print(a.sum(dtype=np.int8)) # -56, wrapped around in int8
f = np.full(1_000_000, 0.1, dtype=np.float32)
print(f.mean(dtype=np.float64)) # accumulates in float64The platform integer is int64 on most 64-bit Linux and macOS systems. On Windows with NumPy versions before 2.0, it is int32.
NaN, empty axes, and where
NaN values propagate through ordinary reductions. One NaN makes the whole result NaN. The nan variants skip them.
import numpy as np
x = np.array([1.0, np.nan, 3.0])
print(x.sum()) # nan
print(np.nansum(x)) # 4.0
print(np.nanmean(x)) # 2.0Empty axes follow the mathematical identity for the operation. A sum over nothing is 0 and a product over nothing is 1. max and min have no identity, so they raise an error unless you supply initial. mean of an empty array returns NaN and emits a RuntimeWarning.
import numpy as np
e = np.zeros((0, 3))
print(e.sum(axis=0)) # [0. 0. 0.]
print(np.max(e, axis=0, initial=-np.inf)) # [-inf -inf -inf]Most reductions also accept where=, a boolean mask that selects which elements take part. For max and min it requires initial. np.sum(a, where=a > 0) sums only the positive values. This is the reduction counterpart of boolean indexing, and it avoids building a temporary filtered array.
Reductions versus accumulations
np.cumsum and np.cumprod look like reductions but keep the axis. They return running totals with the same length along that axis.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.cumsum(axis=1))
# [[ 1 3 6]
# [ 4 9 15]]Performance notes
Reductions run in compiled loops, so they are much faster than Python loops over elements. Two details are worth knowing.
a.sum(axis=...)allocates only the small result. Chaining reductions on the output of a big expression, such as((a - b) ** 2).sum(), still builds the full temporary array first.- Reducing along the contiguous (last) axis of a C-ordered array reads memory sequentially. Other axes can be slower on very large arrays. Measure before restructuring anything.
Exercise
Given d = np.arange(24).reshape(2, 3, 4), what is the shape of d.mean(axis=(0, 2), keepdims=True)? Then write one expression that subtracts, from every element, the mean of its slice along axis 1 (the slice that shares the same indices on axes 0 and 2).
Show answer
The shape is (1, 3, 1), because axes 0 and 2 are reduced to length 1 and axis 1 keeps length 3. For the second part, use d - d.mean(axis=1, keepdims=True). The mean has shape (2, 1, 4), which broadcasts against (2, 3, 4) and subtracts each slice's mean along axis 1.
Exercise
A (4, 4) array p holds counts. p / p.sum(axis=0) runs without error. Does it divide each row or each column by its total? What is the version that normalizes each row, and why is the shape check not enough to catch the mistake?
Show answer
p.sum(axis=0) has shape (4,), which broadcasts along the last axis, so each column j is divided by the total of column j. This normalizes columns. To normalize rows, use p / p.sum(axis=1, keepdims=True). On a square array both shapes broadcast, so NumPy raises no error. Only checking the result, for example allclose(result.sum(axis=1), 1), reveals the mistake.