Sub topic 7
Normalizing and Centering with Aggregates
This chapter assumes you can create arrays with np.array and np.arange, read an array's shape, and use sum and mean with the axis argument. It shows how to combine an aggregate with the original array so you can normalize rows and center columns.
The idea: subtract or divide by an aggregate
Many data tasks compare each value to a summary of its row or column. Two common examples:
- Normalizing divides each value by a total so that a row sums to 1.
- Centering subtracts a mean so that a column averages 0.
Both need an aggregate and the original array to line up in shape. NumPy lines them up through broadcasting. Broadcasting compares shapes from the last dimension backward. Two dimensions are compatible when they are equal or when one of them is 1.
Normalizing rows
Suppose each row holds counts for one item, and you want each row to show shares of its own total.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
row_totals = a.sum(axis=1, keepdims=True)
print(row_totals.shape) # (2, 1)
shares = a / row_totals
print(shares.sum(axis=1)) # [1. 1.]row_totals has shape (2, 1). Broadcasting stretches its length-1 column across the 3 columns of a, so each row is divided by its own total. Without keepdims=True, the total would have shape (2,), and the next section shows why that fails.
Centering columns
Column centering subtracts each column's mean from that column.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
centered = a - a.mean(axis=0)
print(centered)
# [[-1.5 -1.5 -1.5]
# [ 1.5 1.5 1.5]]
print(centered.mean(axis=0)) # [0. 0. 0.]Here a.mean(axis=0) has shape (3,). Shape (2, 3) against (3,) is compatible, because NumPy treats the missing leading dimension as 1. So keepdims is optional for column operations on a 2D array. Adding it does no harm and gives the same result.
Why row operations need keepdims
Row aggregates are where mistakes happen. This diagram shows how the shapes meet.
With shape (2,), NumPy compares the last dimensions, 3 and 2, and raises an error. Worse, if the array were square, such as (3, 3), the shapes (3, 3) and (3,) would be compatible. The code would run without an error, but it would divide each column by the wrong value. Using keepdims=True for row aggregates avoids this silent bug.
Combining both steps
You can chain the two operations. This standardizes each column to mean 0 and standard deviation 1.
import numpy as np
a = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 9.0, 8.0]])
z = (a - a.mean(axis=0)) / a.std(axis=0)
print(z.mean(axis=0).round(6)) # [0. 0. 0.]
print(z.std(axis=0).round(6)) # [1. 1. 1.]A column whose standard deviation is 0 would cause a division by zero and produce nan or inf. Check for that before dividing real data.
Quick reference
| Goal | Expression | Aggregate shape for `(2, 3)` input |
|---|---|---|
| Row shares | `a / a.sum(axis=1, keepdims=True)` | `(2, 1)` |
| Center columns | `a - a.mean(axis=0)` | `(3,)` |
| Center rows | `a - a.mean(axis=1, keepdims=True)` | `(2, 1)` |
Exercise
Given a = np.array([[2, 4], [6, 12]]), write one expression that centers each row so every row has mean 0. What does it return?
Show answer
a - a.mean(axis=1, keepdims=True). The row means are 3 and 9, with shape (2, 1). The result is [[-1., 1.], [-3., 3.]].