Broadcasting is how NumPy does arithmetic on arrays of different shapes without copying data or writing loops. It lets you add a number to a whole matrix, subtract each column’s mean, or apply a tax rate per column in one line.
What You Will Learn
- Scalar and vector broadcasting
- The broadcasting rules
- Row vs column broadcasting
- Centering data by column means
- Reading broadcasting errors
Prerequisites
Examples
import numpy as np
a = np.array([1, 2, 3])
print(a + 10) # scalar is stretched to every element
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m + a) # row (3,) is added to each row of (2, 3)
col = np.array([[10], [20]])
print(m + col) # column (2, 1) is added to each column
[11 12 13] [[2 4 6] [5 7 9]] [[11 12 13] [24 25 26]]
The Rules
- Compare shapes from the right (last dimension first).
- Two dimensions are compatible if they are equal or one of them is 1.
- Missing dimensions on the left are treated as 1.
- A dimension of size 1 is stretched to match the other.
| Shape A | Shape B | Result |
|---|---|---|
| (2, 3) | (3,) | (2, 3) ✓ |
| (2, 3) | (2, 1) | (2, 3) ✓ |
| (3, 1) | (1, 4) | (3, 4) ✓ |
| (2, 3) | (2,) | Error ✗ – 3 vs 2 |
print(np.ones((3, 1)).shape, np.ones((1, 4)).shape, (np.ones((3, 1)) + np.ones((1, 4))).shape)
try:
m + np.array([1, 2])
except ValueError as e:
print("ValueError:", e)
(3, 1) (1, 4) (3, 4) ValueError: operands could not be broadcast together with shapes (2,3) (2,)
Explanation: To add [1, 2] to each column of m, reshape it into a column: m + np.array([1, 2])[:, None] (shape (2, 1)).
Real Uses
# centre each column (feature) by subtracting its mean
print((m - m.mean(axis=0)).round(2))
# apply 5% GST to column 1 and 18% to column 2
prices = np.array([[100, 250], [80, 120], [60, 300]])
gst = np.array([0.05, 0.18])
print(prices * (1 + gst))
[[-1.5 -1.5 -1.5] [ 1.5 1.5 1.5]] [[105. 295. ] [ 84. 141.6] [ 63. 354. ]]
Explanation: m.mean(axis=0) has shape (3,), so it is subtracted from every row – exactly what feature scaling and StandardScaler do. The GST rates broadcast across every product row.
Series
NumPy series: Introduction · Creating Arrays · Data Types · Slicing & Indexing · Array Manipulation · Broadcasting · Math Functions · Statistical Functions · Random · Linear Algebra · NumPy vs Pandas
Interview Questions
Q: What is broadcasting?
NumPy’s rule for operating on arrays of different shapes by virtually stretching size-1 dimensions.
Q: Can (4, 3) and (4,) be added?
No – trailing dimensions 3 and 4 differ; reshape to (4, 1) first.
Practice Exercises
- Normalise each column of a (5, 3) array to the 0–1 range using min and max with broadcasting.
- Create a 10×10 multiplication table with np.arange(1, 11) and broadcasting.
Summary
Broadcasting compares shapes from the right; equal sizes or 1s are compatible, and size-1 dimensions stretch. It replaces loops for row/column-wise operations.
Machine Learning Tutorials, Courses and Certifications