Aggregations
Reduce an array to a summary such as a sum, mean, min or max, optionally per axis.
Syntax
array.mean(axis=0)Aggregations collapse many values into one summary number: sum, mean, min, max, std.
Axis matters
By default they reduce the whole array. Pass axis=0 to reduce down the rows (one result per column) or axis=1 to reduce across columns (one per row).
Example
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum()) # 21 (everything)
print(a.sum(axis=0)) # [5 7 9] (per column)
print(a.sum(axis=1)) # [ 6 15] (per row)
print(a.mean()) # 3.5
print(a.max(axis=1)) # [3 6]When to use it
- A data scientist calls np.mean(X, axis=0) to compute per-feature means across 50,000 training samples for normalisation.
- A quality engineer uses np.min and np.max along the time axis of sensor readings to detect extreme values in a manufacturing dataset.
- An ML researcher tracks np.mean(losses) and np.std(losses) after each training epoch to monitor model convergence stability.
More examples
Basic aggregation functions
Demonstrates the five most common aggregation functions on a 1D array: sum, mean, min, max, and standard deviation.
import numpy as np
data = np.array([4, 7, 13, 2, 9, 1])
print(np.sum(data)) # 36
print(np.mean(data)) # 6.0
print(np.min(data)) # 1
print(np.max(data)) # 13
print(np.std(data)) # standard deviationAxis-wise aggregation on matrix
Uses the axis parameter to compute column-wise means and row-wise sums from a matrix, essential for per-feature and per-sample statistics.
import numpy as np
X = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(np.mean(X, axis=0)) # column means: [4, 5, 6]
print(np.sum(X, axis=1)) # row sums: [6, 15, 24]Argmin and argmax for index lookup
Uses np.argmin to find the epoch index where the training loss was lowest, a common pattern in model checkpointing.
import numpy as np
losses = np.array([0.82, 0.65, 0.51, 0.49, 0.53])
best_epoch = np.argmin(losses)
print(f'Best epoch: {best_epoch}, loss: {losses[best_epoch]}')
Discussion