Sub topic 7
Reductions and the axis argument
This chapter assumes you can create NumPy arrays, read their shape and ndim, and apply elementwise operations such as a + 1 or np.sqrt(a). It also assumes basic Python and the idea of a matrix as rows and columns. Everything here builds on the previous chapter's idea that an array operation works on whole arrays at once.
What a reduction is
A reduction takes many values and combines them into fewer values. sum, mean, max and std are reductions. An elementwise function returns an array of the same shape as its input. A reduction returns an array with fewer elements, or a single scalar.
Without arguments, a reduction collapses the whole array:
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 axis argument chooses which dimension to collapse. Reductions are available both as methods (x.sum()) and as functions (np.sum(x)). The two forms behave the same.
The axis rule
Think of axis=k as "walk along dimension k and combine the values you meet". That dimension disappears from the result's shape, and the remaining dimensions stay in their original order.
For x with shape (2, 3):
axis=0combines the 2 rows into one. Each column is reduced, and the result has shape(3,).axis=1combines the 3 columns in each row. Each row is reduced, and the result has shape(2,).
People often misread axis=0 as "operate on rows". It is better to remember that the named axis is the one that vanishes.
Three dimensions, negative axes and tuples
The rule is the same for any number of dimensions:
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a.sum(axis=0).shape) # (3, 4)
print(a.sum(axis=1).shape) # (2, 4)
print(a.sum(axis=2).shape) # (2, 3)
print(a.sum(axis=-1).shape) # (2, 3), same as axis=2
print(a.sum(axis=(0, 2))) # [ 60 92 124]A negative axis counts from the end, so axis=-1 always means the last dimension. This is useful in code that must work for arrays of different dimensionality, such as the last-axis distance sum you will see in a later chapter.
A tuple of axes reduces several dimensions in one call. With axis=(0, 2) only dimension 1 survives, so the result has shape (3,). Each entry is the sum of all 8 values that share the same index along dimension 1. An integer axis reduces one dimension, axis=None (the default) reduces all of them, and a tuple reduces a chosen set.
Keeping the reduced axis with keepdims
Normally the reduced axis is dropped. With keepdims=True it stays as a dimension of length 1:
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a.sum(axis=1).shape) # (2, 4)
print(a.sum(axis=1, keepdims=True).shape) # (2, 1, 4)The length-1 axis matters because broadcasting can stretch it back to the original size. That lets you combine a reduction with the array it came from, for example subtracting row means from each row. The next chapter covers the broadcasting rules in detail. For now, remember the shape effect: (2, 3, 4) reduced over axis 1 with keepdims=True gives (2, 1, 4).
Common reductions
| Function | Result | Notes |
|---|---|---|
| `sum`, `prod` | Total, product | Integer input stays integer. |
| `mean` | Average | Always returns a float for integer input. |
| `min`, `max` | Smallest, largest value | Raise `ValueError` on empty input. |
| `std`, `var` | Spread | `ddof=0` by default. |
| `any`, `all` | Boolean | True if at least one or every element is truthy. |
| `argmin`, `argmax` | Index of the extreme | Index into the flattened array when `axis` is omitted. |
All of them accept axis and keepdims, except that the arg functions return indices, so their output is integer.
Index-returning reductions
argmax returns where the maximum is, not what it is:
import numpy as np
s = np.array([[3, 9, 2],
[7, 1, 8]])
print(s.argmax()) # 1, position in the flattened array
print(s.argmax(axis=0)) # [1 0 1], row index of each column's maximum
print(s.argmax(axis=1)) # [1 2], column index of each row's maximumWith axis=None the array is treated as flat, so the answer 1 refers to the element 9 at flat position 1. Use np.unravel_index(s.argmax(), s.shape) to convert a flat index back to (row, column).
Counting with booleans
Comparisons produce boolean arrays, and True counts as 1 in a sum. This gives a compact way to count matches:
import numpy as np
m = np.array([[1, 5, 2],
[8, 3, 9]])
mask = m > 4
print(mask.sum()) # 3, how many values exceed 4
print(mask.sum(axis=0)) # [1 1 1], per column
print(mask.sum(axis=1)) # [1 2], per row
print(mask.mean()) # 0.5, the fraction that exceed 4
print((m > 0).all()) # True
print((m > 8).any()) # TrueThe mean of a boolean array is the fraction of True values, which is often the quantity you want.
Edge cases and gotchas
NaN poisons ordinary reductions
If any value is NaN, sum, mean, min and max return NaN. The nan variants skip those values:
import numpy as np
v = np.array([1.0, np.nan, 3.0])
print(v.sum()) # nan
print(np.nansum(v)) # 4.0
print(np.nanmean(v)) # 2.0np.nanmean divides by the count of non-NaN values, not by the original length. Silently skipping NaN can hide a data-quality problem, so check np.isnan(v).sum() first when the NaN count should be zero.
Accumulator dtype
Reductions choose an accumulator type. Summing small integer types such as uint8 promotes to a larger platform integer, so the sum does not wrap around. If you force the output type, wrap-around is possible:
import numpy as np
b = np.array([200, 100], dtype=np.uint8)
print(b.sum()) # 300
print(b.sum(dtype=np.uint8)) # 44, because 300 wraps modulo 256Pass dtype= only when you want to control precision. A common use is dtype=np.float64 to accumulate float32 data more accurately.
Standard deviation and ddof
np.std and np.var divide by N by default (ddof=0), which is the population formula. Pandas and many statistics texts divide by N - 1 for sample estimates. Set ddof=1 for that:
import numpy as np
d = np.array([1.0, 2.0, 3.0, 4.0])
print(round(d.std(), 3)) # 1.118
print(round(d.std(ddof=1), 3)) # 1.291Empty arrays
Some reductions have a natural answer for no data. np.array([]).sum() is 0.0 and prod is 1.0. min and max have no such answer and raise ValueError. Supply initial= to give them one:
import numpy as np
e = np.array([])
print(e.sum()) # 0.0
print(np.max(e, initial=-np.inf)) # -infmean of an empty array returns nan and emits a RuntimeWarning.
Axis out of range
Asking for a dimension that does not exist raises AxisError. It is a subclass of both ValueError and IndexError, so either one catches it:
import numpy as np
x = np.ones((2, 3))
try:
x.sum(axis=2)
except ValueError as err:
print('error:', err) # error: axis 2 is out of bounds for array of dimension 2This error often means the array has fewer dimensions than you assumed, for example after an earlier reduction dropped one.
Reductions versus accumulations
np.cumsum and np.cumprod also take an axis, but they are not reductions. They return running totals and keep the input's shape. np.cumsum(x, axis=1) for a (2, 3) array returns a (2, 3) array. Likewise np.sort(x, axis=0) keeps the shape. The test is the shape: if the named axis disappears, it is a reduction.
Choosing between axis, keepdims and tuples
- Use a plain
axis=kwhen you want a smaller array of per-row or per-column summaries. - Add
keepdims=Truewhen the result will be combined with the original array by broadcasting. - Use a tuple such as
axis=(1, 2)to summarize each item in a batch, for example the mean of every image in an array shaped(batch, height, width). - Use
axis=Noneonly when you truly want one number for everything.
Exercise
Let t = np.arange(60).reshape(3, 4, 5). What is the shape of t.max(axis=1), of t.max(axis=(0, 2)), and of t.max(axis=1, keepdims=True)? Which call would you use to get one maximum per slice along the first dimension?
Show answer
t.max(axis=1) has shape (3, 5), because dimension 1 (length 4) is removed. t.max(axis=(0, 2)) has shape (4,), because dimensions 0 and 2 are removed. t.max(axis=1, keepdims=True) has shape (3, 1, 5). For one maximum per slice along the first dimension, reduce over the other two axes: t.max(axis=(1, 2)), which has shape (3,).
Exercise
A 2-D array scores has one row per student and one column per exam. Write expressions for the average score of each student, the average score of each exam, and the number of students who scored above 90 on each exam.
Show answer
Average per student collapses the exam axis: scores.mean(axis=1). Average per exam collapses the student axis: scores.mean(axis=0). The count above 90 per exam is (scores > 90).sum(axis=0), because True counts as 1 and the student axis is the one that disappears.