Aggregations

NumPy arrays come with built-in methods for summarizing their data — sums, averages, minimums, maximums — and for 2D arrays, an axis argument that controls whether you're summarizing down the columns or across the rows.

Whole-array aggregations

>>> a small gradebook
import numpy as np

scores = np.array([[80, 90, 70], [60, 85, 95]])
print(scores.sum())
print(scores.mean())
print(scores.min())
print(scores.max())
Output
480
80.0
60
95

With no axis specified, every aggregation method treats the array as one flat collection of values — .sum() adds all 6 numbers, .mean() averages all 6, and so on.

Aggregating along an axis

Pass axis=0 to aggregate down each column (collapsing the rows), or axis=1 to aggregate across each row (collapsing the columns):

>>> per-column and per-row totals
print(scores.sum(axis=0))
print(scores.sum(axis=1))
Output
[140 175 165]
[240 240]

scores.sum(axis=0) gives 3 numbers — one total per column, added down each column (80+60=140, 90+85=175, 70+95=165). scores.sum(axis=1) gives 2 numbers — one total per row, added across each row (80+90+70=240, 60+85+95=240).

Note: axis=0 and axis=1 trip almost everyone up at first, because it's easy to expect axis=0 to mean "row 0" or "operate on rows." Think of it instead as "the axis that disappears": axis=0 collapses the row axis, leaving one result per column; axis=1 collapses the column axis, leaving one result per row.