Broadcasting helps us do math on arrays of different shapes easily. It saves time and code by avoiding loops.
0
0
Common broadcasting patterns in NumPy
Introduction
Adding a single number to every element in a list of numbers.
Multiplying each row of a table by a different number.
Subtracting a small array from a bigger array with matching dimensions.
Scaling columns of data by different factors without writing loops.
Applying a function to each element with a different parameter per row or column.
Syntax
NumPy
result = array1 + array2
# or other math operations like -, *, /Arrays must have compatible shapes for broadcasting.
Broadcasting automatically expands smaller arrays to match bigger ones.
Examples
Adds 5 to each element of the array.
NumPy
import numpy as np # Add a scalar to a 1D array arr = np.array([1, 2, 3]) result = arr + 5 print(result)
Each row of arr2d is multiplied element-wise by arr1d.
NumPy
import numpy as np # Multiply a 2D array by a 1D array (broadcast along columns) arr2d = np.array([[1, 2, 3], [4, 5, 6]]) arr1d = np.array([10, 20, 30]) result = arr2d * arr1d print(result)
Subtracts 1 from first row and 2 from second row across all columns.
NumPy
import numpy as np # Subtract a column vector from a 2D array arr2d = np.array([[5, 5, 5], [10, 10, 10]]) col_vec = np.array([[1], [2]]) result = arr2d - col_vec print(result)
Sample Program
This adds the vector to each row of the matrix. Broadcasting repeats the vector for each row automatically.
NumPy
import numpy as np # Create a 2D array (3 rows, 4 columns) matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Create a 1D array with 4 elements vector = np.array([10, 20, 30, 40]) # Add vector to each row of matrix using broadcasting result = matrix + vector print(result)
OutputSuccess
Important Notes
Broadcasting works when trailing dimensions match or one of them is 1.
If shapes are not compatible, NumPy will raise an error.
Broadcasting avoids slow loops and makes code cleaner and faster.
Summary
Broadcasting lets you do math on arrays with different shapes easily.
Common patterns include adding scalars, vectors to matrices, or column vectors to 2D arrays.
It saves time and makes code simpler without writing loops.