How does broadcasting work?

QuestionsQuestions4 SkillsProNumPy Universal FunctionsSep, 11 2025
0149

Broadcasting in NumPy allows for element-wise operations between arrays of different shapes. It automatically expands the smaller array across the larger array so that they have compatible shapes for operations. Here’s how it works:

  1. Shape Alignment: NumPy compares the shapes of the arrays from the trailing dimensions. If the dimensions are equal or one of them is 1, they are considered compatible.

  2. Expansion: If the arrays have different shapes, NumPy "broadcasts" the smaller array across the larger one by virtually replicating it along the dimensions where it has size 1.

  3. Element-wise Operations: Once the shapes are compatible, you can perform element-wise operations like addition, subtraction, multiplication, and division.

Example

import numpy as np

# Creating two arrays of different shapes
array1 = np.array([1, 2, 3])          # Shape (3,)
array2 = np.array([[4, 5, 6],          # Shape (2, 3)
                   [7, 8, 9]])

# Broadcasting the smaller array to the larger array
result_add = array1 + array2
result_sub = array1 - array2
result_mul = array1 * array2
result_div = array1 / array2

print("Addition:\n", result_add)
print("Subtraction:\n", result_sub)
print("Multiplication:\n", result_mul)
print("Division:\n", result_div)

Output

Addition:
 [[ 5  7  9]
 [ 8 10 12]]

Subtraction:
 [[-3 -3 -3]
 [-6 -6 -6]]

Multiplication:
 [[ 4 10 18]
 [ 7 16 27]]

Division:
 [[0.25       0.4        0.5       ]
 [0.14285714 0.25       0.33333333]]

In this example, array1 is broadcasted to match the shape of array2, allowing for element-wise operations.

0 Comments

no data
Be the first to share your comment!