Aggregations and Axis
Python · NumPy Library
Theory
Aggregations reduce many values to one: sum, mean, min, max, std, plus argmin and argmax, which return the position of the smallest or largest value. Called with no axis they summarise the whole array. On a 2-D array the axis argument decides the direction: axis=0 collapses the rows and gives one result per column, while axis=1 collapses the columns and gives one result per row.
For a table of 3 stores (rows) by 3 months (columns), sales.sum(axis=1) is each store's total and sales.sum(axis=0) is each month's total across stores. sales.argmax(axis=1) tells you which month was best for each store. np.cumsum gives running totals, keepdims=True keeps the reduced axis so the result can be broadcast back, and the nan-versions (np.nansum, np.nanmean) skip missing values.
Why we use it
Totals, averages and best or worst positions are the core of every report. The axis argument lets you get per-row or per-column summaries of a whole table in one call instead of writing nested loops.
When to use it
Use axis=0 for per-column (per-feature) statistics and axis=1 for per-row (per-record) ones. Use argmax when you need where the maximum is, not its value. If the data has labels or groups, pandas groupby is often clearer.
How it works
- 2-D array (rows x columns)
- Need one number for the whole array? Yes: Call a.sum() with no axis. No: Choose an axis.
- Summary per column? Yes: axis=0 collapses rows. No: axis=1 collapses columns (per row).
- Need the position of the max? use argmax instead of max
- 1-D result with one value per column or row
Syntax
a.sum() a.mean() a.min() a.max() a.std()
a.sum(axis=0) # per column
a.sum(axis=1) # per row
a.argmax(axis=1) np.cumsum(a)Example
sales = np.array([[120, 135], [90, 95]])
print(sales.sum(axis=0)) # per month
print(sales.sum(axis=1)) # per storeKey points
- axis=0 gives one result per column; axis=1 one per row
- No axis means the whole array is reduced to a single value
- argmax / argmin return positions, not values
- cumsum keeps the shape and gives running totals
- keepdims=True keeps a size-1 axis so results broadcast back