Skip to content
NumPy

Broadcasting

Combine arrays of compatible shapes without copying.

#broadcasting#shapes

Code

numpy
import numpy as np

# Add scalar to every element
a = np.array([1, 2, 3])
print(a + 10)

# Add row vector to every row of a matrix
matrix = np.ones((3, 4))
row = np.array([1, 2, 3, 4])
print(matrix + row)

# Normalize columns: subtract mean, divide by std
data = np.random.rand(5, 3)
mean = data.mean(axis=0)
std = data.std(axis=0)
normalized = (data - mean) / std

# Outer product via broadcasting
outer = np.arange(3).reshape(3, 1) * np.arange(4).reshape(1, 4)