Broadcasting lets you do math on arrays of different sizes easily. It saves time and code by matching shapes automatically.
0
0
Broadcasting rules 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 smaller array from a bigger array without writing loops.
Applying a formula to data with different shapes but related dimensions.
Syntax
NumPy
When performing operations on two arrays, NumPy compares their shapes element-wise from right to left. Rules: 1. If the dimensions are equal, or one of them is 1, they are compatible. 2. If dimensions differ and neither is 1, broadcasting is not possible. The smaller array is 'stretched' to match the larger one without copying data.
Broadcasting does not actually copy data; it creates a view that behaves like the larger shape.
Shapes are compared from the last dimension backward.
Examples
A single number (scalar) is added to each element of the array.
NumPy
import numpy as np # Example 1: Adding scalar to array arr = np.array([1, 2, 3]) result = arr + 5 print(result)
The (3,1) array is broadcast across the 4 columns to match (3,4).
NumPy
import numpy as np # Example 2: Adding array with shape (3,1) to (3,4) a = np.array([[1], [2], [3]]) # shape (3,1) b = np.array([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]) # shape (3,4) result = a + b print(result)
Arrays with incompatible shapes cause an error.
NumPy
import numpy as np # Example 3: Shapes not compatible try: a = np.array([1, 2, 3]) # shape (3,) b = np.array([[1, 2], [3, 4]]) # shape (2,2) result = a + b except ValueError as e: print(e)
Sample Program
Here, array2 with shape (3,) is broadcast across the rows of array1 with shape (2,3). The addition works element-wise.
NumPy
import numpy as np # Create arrays with different shapes array1 = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2,3) array2 = np.array([10, 20, 30]) # shape (3,) # Add arrays using broadcasting result = array1 + array2 print("array1 shape:", array1.shape) print("array2 shape:", array2.shape) print("result shape:", result.shape) print("result:") print(result)
OutputSuccess
Important Notes
Broadcasting works only when dimensions are compatible as per the rules.
It helps avoid writing loops and makes code faster and cleaner.
Always check shapes if you get unexpected results or errors.
Summary
Broadcasting lets NumPy do math on arrays with different shapes by matching dimensions.
It compares shapes from right to left and stretches dimensions of size 1.
This saves time and code by avoiding explicit loops.