0
0
NumPydata~5 mins

Avoiding broadcasting mistakes in NumPy

Choose your learning style9 modes available
Introduction

Broadcasting lets us do math on arrays of different shapes easily. But if shapes don't match well, results can be wrong. Avoiding mistakes helps get correct answers.

Adding a list of numbers to a table of data with different rows and columns
Multiplying a single number or row by a whole matrix
Applying a function to each row or column without writing loops
Combining arrays from different sources that may have different shapes
Syntax
NumPy
result = array1 + array2

Arrays must have compatible shapes for broadcasting.

Broadcasting compares shapes from the right side, matching dimensions or using 1.

Examples
Adding a 1D array to each row of a 2D array works because shapes (2,3) and (3,) are compatible.
NumPy
import numpy as np

# Correct broadcasting
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([10, 20, 30])
C = A + B
print(C)
Shapes (2,2) and (3,) do not match, so broadcasting fails and raises an error.
NumPy
import numpy as np

# Mistake: incompatible shapes
A = np.array([[1, 2], [3, 4]])
B = np.array([10, 20, 30])
C = A + B  # This will cause an error
Reshaping B to (2,1) allows broadcasting with A's shape (2,2).
NumPy
import numpy as np

# Using reshape to fix shape
A = np.array([[1, 2], [3, 4]])
B = np.array([10, 20])
C = A + B.reshape(2, 1)
print(C)
Sample Program

This program shows adding a vector to each row of a matrix correctly, then tries a wrong shape causing an error, and finally fixes it by reshaping.

NumPy
import numpy as np

# Define a 2D array with 3 rows and 2 columns
matrix = np.array([[1, 2], [3, 4], [5, 6]])

# Define a 1D array with 2 elements
vector = np.array([10, 20])

# Add vector to each row of matrix (correct broadcasting)
result_correct = matrix + vector
print("Correct broadcasting result:")
print(result_correct)

# Define a 1D array with 3 elements (wrong shape for broadcasting)
wrong_vector = np.array([10, 20, 30])

try:
    # This will raise an error because shapes don't match
    result_wrong = matrix + wrong_vector
except ValueError as e:
    print("Broadcasting error:", e)

# Fix by reshaping wrong_vector to (3,1)
fixed_vector = wrong_vector.reshape(3, 1)
result_fixed = matrix + fixed_vector
print("Fixed broadcasting result:")
print(result_fixed)
OutputSuccess
Important Notes

Always check array shapes before operations to avoid silent mistakes.

Use array.shape to see dimensions.

Reshape arrays with reshape() to make shapes compatible.

Summary

Broadcasting lets arrays with different shapes work together if compatible.

Shape mismatch causes errors or wrong results.

Check and fix shapes before math operations to avoid mistakes.