0PricingLogin
Pandas & NumPy Academy · Lesson

Broadcasting Rules

Understand NumPy's broadcasting rules so you can add a 1-D array to every row of a 2-D array without explicit replication.

The Problem Broadcasting Solves

Broadcasting lets NumPy combine arrays of different but compatible shapes without copying data — the smaller one is stretched to fit the larger.

import numpy as np

# Adding a scalar to an array is the simplest broadcast
a = np.array([1, 2, 3])
print(a + 10)  # [11 12 13]
# Scalar 10 is 'broadcast' to shape (3,)

Broadcasting Rule 1: Prepend 1s

NumPy lines up shapes from the right. If one array has fewer dimensions, it pads the left with 1s — so a (3,) array acts like (1, 3) next to a (4, 3) one.

import numpy as np

m = np.ones((4, 3))
v = np.array([10, 20, 30])  # shape (3,) -> treated as (1, 3)

result = m + v   # shape (4, 3)
print(result)
# [[11. 21. 31.]
#  [11. 21. 31.]
#  [11. 21. 31.]
#  [11. 21. 31.]]

All lessons in this course

  1. Universal Functions (ufuncs)
  2. Aggregation Functions
  3. Broadcasting Rules
  4. Boolean Masking and Fancy Indexing
← Back to Pandas & NumPy Academy