Sub topic 2
Predicting the Shape of a NumPy Aggregation Result
Assume you know basic Python, NumPy array creation, indexing, and shape. An aggregation combines values with an operation such as sum, mean, min, or max.
Predicting the Shape of the Result
For a two-dimensional array, axis identifies the dimension that the function reduces. NumPy removes that dimension from the result.
Consider an array with shape (2, 3):
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=0)) # [5 7 9]
print(a.sum(axis=0).shape) # (3,)
print(a.sum(axis=1)) # [ 6 15]
print(a.sum(axis=1).shape) # (2,)| Operation | Reduced dimension | Result shape |
|---|---|---|
| `a.sum(axis=0)` | Rows | `(3,)` |
| `a.sum(axis=1)` | Columns | `(2,)` |
| `a.sum()` | Both dimensions | `()` |
axis=0 combines values down the rows and produces one value for each column. axis=1 combines values across the columns and produces one value for each row. With no axis, every value contributes to one scalar.
Keeping the Reduced Axis with `keepdims`
Set keepdims=True when the result must retain the reduced dimension with length one.
column_means = a.mean(axis=0, keepdims=True)
row_totals = a.sum(axis=1, keepdims=True)
print(column_means.shape) # (1, 3)
print(row_totals.shape) # (2, 1)Without keepdims, these shapes would be (3,) and (2,).
Normalizing and Centering with Aggregates
Broadcasting lets NumPy apply a smaller aggregate to the original array.
shares = a / a.sum(axis=1, keepdims=True)
centered = a - a.mean(axis=0, keepdims=True)
print(shares)
print(centered)shares divides each row by its row total, so each row sums to 1. centered subtracts each column's mean from that column. The (2, 1) row totals broadcast across columns, while the (1, 3) column means broadcast across rows.
Exercise
What are the shapes of a.max(axis=0, keepdims=True) and a.min(axis=1) when a.shape is (2, 3)?
Show answer
Their shapes are (1, 3) and (2,).