Aggregations and Axis
An aggregation reduces many values to a few summary numbers: a total, an average, a maximum. You've met sum and prod in the ufunc lessons; NumPy has a whole family of them, and they all share the same axis argument.
| Function / method | Returns |
|---|---|
sum, prod |
total, product |
mean, median |
average, middle value |
std, var |
standard deviation, variance |
min, max |
smallest, largest |
argmin, argmax |
position of smallest / largest |
ptp |
range: max − min |
percentile, quantile |
e.g. the 90th percentile |
any, all |
is any / every element true? |
cumsum, cumprod |
running totals (same shape, not a reduction) |
Most exist both as functions (np.mean(a)) and as array methods (a.mean()). The exceptions are median, percentile, quantile and ptp, which you call as np.median(a) etc.
Whole-array statistics
import numpy as np
response_ms = np.array([120, 95, 310, 101, 88, 240, 99, 105])
print("mean: ", response_ms.mean())
print("median:", np.median(response_ms))
print("std: ", response_ms.std().round(2))
print("min/max:", response_ms.min(), response_ms.max(), " range:", np.ptp(response_ms))
print("90th percentile:", np.percentile(response_ms, 90))mean: 144.75
median: 103.0
std: 77.68
min/max: 88 310 range: 222
90th percentile: 261.0
The mean (144.75 ms) is pulled up by two slow responses, while the median (103 ms) describes a "typical" request better. Comparing mean and median is a quick way to spot skewed data.
Thinking in axes
For a 2-D array, axis=0 aggregates down the columns (one result per column) and axis=1 across the rows (one result per row). The rule from the Summations lesson holds for every aggregation: the axis you name is the one that disappears.
import numpy as np
# Rows: 4 students. Columns: 3 exams
marks = np.array([[72, 85, 90],
[64, 70, 58],
[88, 92, 95],
[55, 61, 70]])
print("average per exam (axis=0): ", marks.mean(axis=0).round(2))
print("average per student (axis=1):", marks.mean(axis=1).round(2))
print("best student per exam: ", marks.argmax(axis=0))
print("weakest exam per student: ", marks.argmin(axis=1))average per exam (axis=0): [69.75 77. 78.25]
average per student (axis=1): [82.33 64. 91.67 62. ]
best student per exam: [2 2 2]
weakest exam per student: [0 2 0 0]
For a 3-D array the same logic extends. With shape (days, hours, sensors), axis=(0, 1) reduces over days and hours at once, leaving one value per sensor:
import numpy as np
rng = np.random.default_rng(0)
readings = rng.integers(15, 30, size=(7, 24, 3)) # 7 days, 24 hours, 3 sensors
print(readings.shape)
print("per sensor:", readings.mean(axis=(0, 1)).round(2))
print("daily max per sensor shape:", readings.max(axis=1).shape)(7, 24, 3)
per sensor: [22.27 22.57 22.11]
daily max per sensor shape: (7, 3)
any and all
Boolean aggregations answer yes/no questions about the data, overall or per row/column:
import numpy as np
marks = np.array([[72, 85, 90],
[64, 70, 58],
[88, 92, 95],
[55, 61, 70]])
passed = marks >= 60
print("anyone failed anything?", (~passed).any())
print("passed every exam: ", passed.all(axis=1))
print("exams everyone passed: ", passed.all(axis=0))
print("pass rate per exam: ", passed.mean(axis=0))anyone failed anything? True
passed every exam: [ True False True False]
exams everyone passed: [False True False]
pass rate per exam: [0.75 1. 0.75]
Population vs sample statistics: ddof
By default std and var divide by n (the population formula). Statistics on a sample usually divide by n − 1; set ddof=1 ("delta degrees of freedom"). pandas uses ddof=1 by default, so the two libraries can give different answers for the same data:
import numpy as np
data = np.array([4.0, 7.0, 6.0, 3.0, 5.0])
print("divide by n (ddof=0):", data.std().round(4))
print("divide by n - 1 (ddof=1):", data.std(ddof=1).round(4))divide by n (ddof=0): 1.4142
divide by n - 1 (ddof=1): 1.5811
Weighted averages
np.average accepts weights. A course grade where the final exam counts double:
import numpy as np
marks = np.array([[72, 85, 90],
[64, 70, 58]])
weights = np.array([1, 1, 2]) # final exam counts double
print(np.average(marks, axis=1, weights=weights))[84.25 62.5 ]
Test yourself
a has shape (10, 4). What is the shape of a.max(axis=0)?
- (10,)
- (4,)
- (10, 4)
- ()
Which is the better 'typical value' for heavily skewed data?
- The mean
- The median
- The maximum
- The variance
What does ddof=1 change in a.std(ddof=1)?
- It ignores the first element
- It divides by n - 1 instead of n
- It rounds to 1 decimal
- It uses axis 1