Sub topic 3
Aligning Shapes with `np.newaxis` and `keepdims`
Assume you know basic Python, NumPy imports, and the idea of vectors and matrices. This chapter focuses on making array shapes line up without writing loops.
Aligning shapes
np.newaxis adds an axis of length one. A one-dimensional array with shape (3,) becomes a column with shape (3, 1):
import numpy as np
col = np.arange(3)[:, np.newaxis] # (3, 1)
row = np.arange(4) # (4,)
print(col + row)
# [[0 1 2 3]
# [1 2 3 4]
# [2 3 4 5]]keepdims=True keeps a reduced axis as length one. This makes the result ready for broadcasting:
x = np.array([[1., 2., 3.],
[4., 5., 6.]])
row_means = x.mean(axis=1, keepdims=True) # (2, 1)
centered = x - row_means
print(centered)
# [[-1. 0. 1.]
# [-1. 0. 1.]]Broadcasting in practice
Broadcasting compares dimensions from right to left. Two dimensions are compatible when they are equal or one is 1. Missing dimensions act like 1.
This supports centering, scaling, and pairwise calculations. For pairwise distances, reshape points to (n, 1, features) and (1, n, features). Subtraction then creates every pair of differences.
Conditional selection
np.where(condition, if_true, if_false) performs an elementwise choice. Its arguments can also broadcast:
a = np.arange(10)
result = np.where(a > 5, a, 0)
print(result) # [0 0 0 0 0 0 6 7 8 9]Errors and memory cost
A shape (3, 4) cannot add directly to (3,): trailing dimensions 4 and 3 differ. Use v[:, np.newaxis] for shape (3, 1) when each row needs its own value.
Vectorization replaces Python loops with array operations, often improving speed. However, broadcasting can create large temporary arrays. Pairwise differences for n points may require memory proportional to n².
> callout note > Broadcasting changes how NumPy interprets shapes. It does not always avoid allocating the resulting data.
Matrix products
Elementwise * multiplies matching entries. Matrix multiplication uses @:
a = np.array([[1, 2], [3, 4]])
b = np.array([[5], [6]])
print(a @ b) # [[17], [39]]For a @ b, the inner dimensions must match: (2, 2) @ (2, 1) produces (2, 1).
Exercise
What shape does np.ones((4, 3)) + np.arange(3) produce, and why?
Show answer
(4, 3), because (3,) broadcasts across the four rows.