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 Data Analysis Python
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 without writing loops.
Applying a formula to all data points with different shapes.
Combining data from different sources with compatible sizes.
Syntax
Data Analysis Python
result = array1 + array2
Arrays must have compatible shapes for broadcasting.
Smaller arrays are 'stretched' to match bigger ones without copying data.
Examples
Adds 5 to each element of the array.
Data Analysis Python
import numpy as np # Add a number to an array arr = np.array([1, 2, 3]) result = arr + 5 print(result)
Each row of arr2d is multiplied element-wise by arr1d.
Data Analysis Python
import numpy as np # Multiply a 2D array by a 1D array arr2d = np.array([[1, 2, 3], [4, 5, 6]]) arr1d = np.array([10, 20, 30]) result = arr2d * arr1d print(result)
Subtracts each element of col_vec from corresponding row in arr2d.
Data Analysis Python
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 program adds the 1D vector to each row of the 3x3 matrix. Broadcasting stretches the vector to match the matrix shape.
Data Analysis Python
import numpy as np # Create a 3x3 array matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Create a 1D array with 3 elements vector = np.array([10, 20, 30]) # Add vector to each row of matrix using broadcasting result = matrix + vector print(result)
OutputSuccess
Important Notes
Broadcasting works when trailing dimensions are equal or one of them is 1.
If shapes are not compatible, Python will raise an error.
Broadcasting does not copy data, so it is memory efficient.
Summary
Broadcasting lets you do math on arrays with different shapes easily.
Smaller arrays are stretched to match bigger ones without copying data.
It saves time and makes code simpler for array operations.