Broadcasting lets you do math on arrays of different shapes easily. It saves time and code by stretching smaller arrays to match bigger ones.
0
0
1D and 2D broadcasting in NumPy
Introduction
Adding a list of numbers to each row of a table of data.
Multiplying each column of a matrix by a single number.
Subtracting a 1D array from each row of a 2D array.
Scaling rows or columns of data without writing loops.
Syntax
NumPy
result = array1 + array2
Arrays must have compatible shapes for broadcasting.
Smaller arrays are 'stretched' without copying data.
Examples
The 1D array b is added to each row of A by stretching b.
NumPy
import numpy as np # 1D array added to each row of 2D array A = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([10, 20, 30]) result = A + b print(result)
Each column of A is multiplied by the corresponding element in b.
NumPy
import numpy as np # 2D array multiplied by 1D array (broadcast on columns) A = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([2, 3, 4]) result = A * b print(result)
Subtracts b from each row of A using broadcasting.
NumPy
import numpy as np # 1D array subtracted from each row of 2D array A = np.array([[5, 6, 7], [8, 9, 10]]) b = np.array([1, 2, 3]) result = A - b print(result)
Sample Program
This program adds a 1D array to each row of a 2D array. Broadcasting stretches the 1D array across rows so addition works element-wise.
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 the 1D array to each row of the 2D array using broadcasting result = matrix + vector print("Original 2D array (matrix):") print(matrix) print("\n1D array (vector):") print(vector) print("\nResult of broadcasting addition:") print(result)
OutputSuccess
Important Notes
Broadcasting works when trailing dimensions match or one of them is 1.
It avoids slow loops by doing operations fast in C code inside numpy.
If shapes are not compatible, numpy will raise an error.
Summary
Broadcasting lets you do math on arrays with different shapes easily.
1D arrays can be added or multiplied across rows or columns of 2D arrays.
It saves time and code by stretching smaller arrays without copying data.