0
0
NumPydata~5 mins

Broadcasting with higher dimensions in NumPy

Choose your learning style9 modes available
Introduction

Broadcasting lets us do math on arrays of different shapes easily. It saves time and code by automatically expanding smaller arrays.

Adding a 1D array to each row of a 2D table of data.
Multiplying a 3D image by a 1D color filter.
Subtracting a single value from every element in a multi-dimensional dataset.
Applying a mask or scale factor across higher dimensional sensor data.
Syntax
NumPy
result = array1 + array2

Arrays must be compatible in shape following broadcasting rules.

Smaller arrays are 'stretched' without copying data.

Examples
Adds 1D array to each row of 2D array by broadcasting.
NumPy
import numpy as np

# 2D array plus 1D array
A = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20, 30])
result = A + b
print(result)
Broadcasts 2D array over last two dimensions of 3D array.
NumPy
import numpy as np

# 3D array plus 2D array
A = np.ones((2, 3, 4))
B = np.arange(3).reshape(3, 1)
result = A + B
print(result.shape)
Broadcasts 1D array over last dimension of 4D array.
NumPy
import numpy as np

# 4D array plus 1D array
A = np.zeros((2, 3, 4, 5))
B = np.array([1, 2, 3, 4, 5])
result = A + B
print(result.shape)
Sample Program

This example adds a 2D array to a 3D array. The 2D array is broadcast across the last two dimensions of the 3D array. This means each 3x4 block in the 3D array has the 2D array added to it row-wise.

NumPy
import numpy as np

# Create a 3D array (2 blocks, 3 rows, 4 columns)
array_3d = np.arange(24).reshape(2, 3, 4)

# Create a 2D array (3 rows, 1 column)
array_2d = np.array([[100], [200], [300]])

# Add 2D array to 3D array using broadcasting
result = array_3d + array_2d

print("3D array shape:", array_3d.shape)
print("2D array shape:", array_2d.shape)
print("Result shape:", result.shape)
print("Result array:")
print(result)
OutputSuccess
Important Notes

Broadcasting does not copy data, so it is memory efficient.

Shapes are compared from right to left when broadcasting.

If dimensions are not compatible, NumPy will raise an error.

Summary

Broadcasting lets you do math on arrays with different shapes easily.

Smaller arrays are stretched to match bigger ones without copying data.

This works well with higher dimensional data like images or time series.