Python Central HubSign in

Data Analytics with Python / Phase 2: Numerical Computing NumPy

Broadcasting in NumPy

Understand NumPy broadcasting rules to perform fast vectorized operations across arrays with different shapes.

What is broadcasting?

Broadcasting is NumPy's ability to perform operations on arrays with different shapes by automatically expanding (virtually) smaller arrays.

This is a major reason NumPy code is concise and fast. Nothing is actually copied in memory — NumPy just repeats the smaller array's values as if it were stretched to fit, without allocating that extra memory.

Simple example: add scalar

Python
import numpy as np
 
arr = np.array([1, 2, 3])
print(arr + 10)  # [11 12 13]

Here, the scalar 10 is broadcast to match the shape (3,).

Example: add vector to matrix

Python
import numpy as np
 
mat = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
vec = np.array([10, 20, 30])
 
print(mat + vec)

vec (shape (3,)) broadcasts across each row.

sketch Broadcasting a row vector across a matrix p5.js
The (3,) vector is virtually stretched down to match every row of the (2, 3) matrix — no extra memory is actually allocated.

Broadcasting rules (must know)

When operating on two arrays, NumPy compares shapes from the trailing dimension (rightmost first) and works backward.

Two dimensions are compatible when:

  1. They are equal, OR
  2. One of them is 1

If dimensions are incompatible → broadcasting error.

Example: column vector + matrix

Python
import numpy as np
 
mat = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
col = np.array([100, 200]).reshape(2, 1)
 
print(mat + col)

col has shape (2, 1) and broadcasts across columns.

Common broadcasting error

Python
import numpy as np
 
mat = np.zeros((2, 3))
vec = np.array([1, 2])
 
# mat + vec -> ValueError (shapes (2,3) and (2,) not compatible)

Fix by reshaping vec to a column vector if that's what you intend:

Python
vec = vec.reshape(2, 1)
print(mat + vec)
diagram Broadcasting compatibility check mermaid
NumPy compares shapes from the trailing dimension inward; each axis pair must match or be 1.

Why broadcasting is useful in analytics

  • Normalize columns: X / X.max(axis=0)
  • Center data: X - X.mean(axis=0)
  • Apply weights: X * weights

Check your understanding

quizCheck yourself
  1. In which order does NumPy compare shapes when broadcasting?

    Show answer

    B — From the trailing dimension (rightmost first) backward — Broadcasting compares shapes starting at the last axis and works backward. Each pair of sizes must be equal or one must be 1.

  2. mat has shape (2, 3) and vec has shape (3,). What is the shape of mat + vec?

    Show answer

    B — (2, 3) — The trailing axes match (3 and 3), so vec is virtually stretched across both rows and the result keeps shape (2, 3).

  3. mat has shape (2, 3) and vec = np.array([1, 2]) has shape (2,). How do you make mat + vec work as a per-row addition?

    Show answer

    A — Use vec.reshape(2, 1) — (2, 3) and (2,) clash on the trailing axis (3 vs 2). Reshaping vec to (2, 1) makes it a column that broadcasts across the columns. vec.T does nothing on a 1D array.

  4. Which expression centers each column of X around zero, as shown in the lesson?

    Show answer

    A — X - X.mean(axis=0) — X.mean(axis=0) gives one mean per column, which broadcasts across all rows. X / X.max(axis=0) normalizes instead of centering.

Next

Continue to: NumPy Arithmetic Operations for element-wise math and matrix operations.

🧪 Try It Yourself

Exercise 1 – Broadcast a Scalar

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Broadcast a Row Vector Across a Matrix

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Fix a Shape Mismatch

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did