sum, mean, std (with axis) (NumPy)

Aggregation functions like sum(), mean(), and std() reduce an array to summary values. With no axis they reduce the whole array to one number; with an axis they reduce along just that dimension.

NumPy

a.sum() adds every element to a scalar, but the axis argument is what makes aggregations powerful on 2-D data. a.sum(axis=0) sums down each column (collapsing the rows), while a.sum(axis=1) sums across each row (collapsing the columns). The same pattern applies to mean, std, var, min, max, and prod.

Remember the 'axis that disappears' rule: the axis you name is the one removed from the result's shape. Summing a (2, 3) array along axis 0 gives a length-3 result. Pass keepdims=True to retain that axis as length 1, which is handy for broadcasting the result back against the original.

These reductions ignore nothing by default, so a single NaN poisons the result; the nan-aware variants nansum, nanmean, and nanstd skip missing values instead.

Syntax

a.sum(axis=None)  |  a.mean(axis=0)  |  a.std(axis=1)

Examples

Python

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.mean(axis=0))

Output:

[2.5 3.5 4.5]

Learn it in a lesson

See also

Back to the Dictionary