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 run sum, mean, min, and max with an axis argument. It also uses keepdims=True, which the previous chapter introduced. Here you will use aggregates to rescale an array: dividing rows by their totals, subtracting column means, and standardizing features. All of these depend on broadcasting.
Why aggregates and arrays meet
Many data tasks need each value compared with a summary of its own row or column. Examples:
- What share of its row total is each cell?
- How far is each value from its column mean?
- Where does each value sit between its column's minimum and maximum?
Each task has two steps. First, reduce the array with an aggregate along one axis. Second, combine that smaller result with the original array. The second step works only if the two shapes are compatible under the broadcasting rules.
The broadcasting rule you need
NumPy compares two shapes starting from the last dimension and moving left. Two dimensions are compatible if they are equal or if one of them is 1. A dimension of length 1 is stretched to match the other. A missing leading dimension is treated as 1.
For a with shape (2, 3), here is how the two possible aggregates line up:
| Aggregate | Result shape | Shape compared with `(2, 3)` | Outcome |
|---|---|---|---|
| `a.sum(axis=0)` | `(3,)` | `(3,)` against the last axis of length 3 | Works, one value per column |
| `a.sum(axis=1)` | `(2,)` | `(2,)` against the last axis of length 3 | Error, 2 does not match 3 |
| `a.sum(axis=1, keepdims=True)` | `(2, 1)` | `(2, 1)` against `(2, 3)` | Works, one value per row |
The pattern is that a column-wise aggregate (axis=0) usually broadcasts without help, because dropping the first axis leaves the trailing axes in place. A row-wise aggregate (axis=1) needs keepdims=True, because the dropped axis is the last one and the leftover shape would line up with the wrong axis.
Normalizing rows with keepdims
Row normalization divides every value by the total of its own row, so each row sums to 1.
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)
print(row_totals)
# [[ 6]
# [15]]
shares = a / row_totals
print(np.round(shares, 3))
# [[0.167 0.333 0.5 ]
# [0.267 0.333 0.4 ]]
print(np.allclose(shares.sum(axis=1), 1.0)) # TrueBroadcasting stretches the (2, 1) column of totals across the three columns. Row 0 is divided by 6 everywhere and row 1 by 15 everywhere. The / operator always does true division, so integer input gives float output.
Instead of keepdims=True, you can add the axis yourself with a.sum(axis=1)[:, np.newaxis], or reshape with .reshape(-1, 1). These give the same shape. keepdims=True is shorter and also works unchanged for higher-dimensional arrays.
Centering columns and rows
Centering subtracts the mean so that the new mean is zero. For columns, axis=0 is enough.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
col_means = a.mean(axis=0)
print(col_means) # [2.5 3.5 4.5]
print(col_means.shape) # (3,)
centered = a - col_means
print(centered)
# [[-1.5 -1.5 -1.5]
# [ 1.5 1.5 1.5]]
print(centered.mean(axis=0)) # [0. 0. 0.]Centering rows follows the same recipe as row normalization and needs keepdims=True.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
row_centered = a - a.mean(axis=1, keepdims=True)
print(row_centered)
# [[-1. 0. 1.]
# [-1. 0. 1.]]Both rows end up as [-1, 0, 1], because each row was a run of consecutive integers and only its offset differed.
The square-array trap
If you drop keepdims=True on a non-square array, NumPy raises an error:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
try:
a / a.sum(axis=1)
except ValueError as e:
print(e)
# operands could not be broadcast together with shapes (2,3) (2,) An error is the good outcome. When the array is square, the shapes (3, 3) and (3,) are compatible, so NumPy does not complain and divides by the wrong thing.
import numpy as np
b = np.arange(1, 10).reshape(3, 3)
wrong = b / b.sum(axis=1) # no error
right = b / b.sum(axis=1, keepdims=True)
print(np.allclose(right.sum(axis=1), 1.0)) # True
print(np.allclose(wrong.sum(axis=1), 1.0)) # FalseIn wrong, the vector of row sums [6, 15, 24] is treated as one divisor per column. The code runs, and the numbers are quietly incorrect. A cheap safeguard is to check a property of the result, such as "every row sums to 1", with np.allclose.
Standardizing and rescaling
Two common feature transformations combine several aggregates in one expression.
Z-score standardization subtracts the column mean and divides by the column standard deviation. The result has mean 0 and standard deviation 1 in each column.
import numpy as np
x = np.array([[1.0, 10.0],
[2.0, 20.0],
[6.0, 60.0]])
z = (x - x.mean(axis=0)) / x.std(axis=0)
print(np.allclose(z.mean(axis=0), 0.0)) # True
print(np.allclose(z.std(axis=0), 1.0)) # TrueBoth aggregates have shape (2,), which broadcasts along the rows. The two columns have very different scales (1 to 6 and 10 to 60), but after standardizing they are identical, because the second column is the first multiplied by 10.
By default np.std uses the population formula (ddof=0). Pass ddof=1 for the sample standard deviation, as pandas does by default. Use one choice consistently, or the standardized columns will not have a standard deviation of exactly 1.
Min-max scaling maps each column to the range from 0 to 1.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
lo = a.min(axis=0)
hi = a.max(axis=0)
scaled = (a - lo) / (hi - lo)
print(scaled)
# [[0. 0. 0.]
# [1. 1. 1.]]Edge cases to plan for
Aggregate-based rescaling divides by a summary value, and that value can be zero.
- A row whose total is 0 gives
0 / 0orx / 0in row normalization, which producesnanorinfwith a runtime warning. - A column with no spread (all values equal) has a standard deviation of 0 and a min-max range of 0. Standardizing or scaling it produces
nan. - A column that contains
nanproduces ananmean, so every value in that column becomesnanafter centering. Usenp.nanmeanandnp.nanstdto skip missing values.
One way to guard against zero divisors is to replace them before dividing.
import numpy as np
a = np.array([[1.0, 2.0, 3.0],
[0.0, 0.0, 0.0]])
totals = a.sum(axis=1, keepdims=True)
safe_totals = np.where(totals == 0, 1.0, totals)
shares = a / safe_totals
print(shares)
# [[0.16666667 0.33333333 0.5 ]
# [0. 0. 0. ]]The all-zero row stays all zeros instead of becoming nan. Whether zeros are the right answer for your data is a modeling decision, so make it deliberately.
In-place operations and dtypes
You can write the result back into the array with -= or /=, which avoids allocating a new array. This works only if the array is already a float type.
import numpy as np
f = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
f -= f.mean(axis=0)
print(f)
# [[-1.5 -1.5 -1.5]
# [ 1.5 1.5 1.5]]
i = np.array([[1, 2, 3],
[4, 5, 6]])
try:
i -= i.mean(axis=0)
except TypeError as e:
print(type(e).__name__) # UFuncTypeErrori.mean(axis=0) is a float array, and NumPy refuses to cast the float result back into integer storage. Convert first with i.astype(float), or use the non-in-place form i = i - i.mean(axis=0), which creates a new float array.
Summary of recipes
| Goal | Expression for a 2-D array `a` |
|---|---|
| Row shares (each row sums to 1) | `a / a.sum(axis=1, keepdims=True)` |
| Column shares | `a / a.sum(axis=0)` |
| Subtract column means | `a - a.mean(axis=0)` |
| Subtract row means | `a - a.mean(axis=1, keepdims=True)` |
| Column z-scores | `(a - a.mean(axis=0)) / a.std(axis=0)` |
| Column min-max scaling | `(a - a.min(axis=0)) / (a.max(axis=0) - a.min(axis=0))` |
Exercise
Given m = np.array([[2.0, 4.0, 6.0], [1.0, 1.0, 4.0]]), write one expression that subtracts each row's mean from that row. What is the shape of the aggregate you used, and what does each row of the result sum to?
Show answer
m - m.mean(axis=1, keepdims=True). The aggregate has shape (2, 1), which broadcasts across the three columns. The result is [[-2., 0., 2.], [-1., -1., 2.]], and each row sums to 0 (up to floating-point rounding).
Exercise
A colleague writes shares = a / a.sum(axis=1) for an array a of shape (4, 4) and sees no error. Explain why the code runs, why the output is wrong, and how to fix it.
Show answer
With shape (4, 4) and an aggregate of shape (4,), broadcasting is allowed, so the vector of row sums is applied along the last axis, meaning one divisor per column instead of one per row. The rows will not sum to 1. Fix it with a / a.sum(axis=1, keepdims=True), so the aggregate has shape (4, 1).
Exercise
For x = np.array([[5.0, 5.0], [5.0, 9.0]]), what happens when you compute min-max scaling on the columns, and why?
Show answer
The first column has min 5 and max 5, so its range is 0. The division 0 / 0 gives nan (with a RuntimeWarning), so the first column of the result is [nan, nan]. The second column scales normally to [0., 1.]. Guard the range, for example with np.where(rng == 0, 1.0, rng), before dividing.