0
0
NumpyConceptBeginner · 3 min read

What is Broadcasting in NumPy: Simple Explanation and Example

In NumPy, broadcasting is a way to perform arithmetic operations on arrays of different shapes by automatically expanding the smaller array to match the larger one. This lets you write concise code without manually reshaping arrays.
⚙️

How It Works

Broadcasting in NumPy works like fitting smaller arrays into bigger ones so they can work together in calculations. Imagine you have a small sticker and a big notebook. Instead of cutting the notebook, you imagine the sticker repeated across the notebook pages so they match in size.

NumPy compares the shapes of two arrays starting from the last dimension. If the dimensions are equal or one of them is 1, it stretches the smaller array along that dimension. This stretching is virtual, so no extra memory is used.

This mechanism allows you to add, multiply, or do other operations on arrays even if their shapes don't exactly match, as long as they follow broadcasting rules.

💻

Example

This example shows adding a 1D array to a 2D array. NumPy automatically broadcasts the 1D array across each row of the 2D array.

python
import numpy as np

array_2d = np.array([[1, 2, 3],
                     [4, 5, 6]])
array_1d = np.array([10, 20, 30])

result = array_2d + array_1d
print(result)
Output
[[11 22 33] [14 25 36]]
🎯

When to Use

Use broadcasting when you want to apply operations between arrays of different shapes without writing loops or manually reshaping. It is very useful in data science for tasks like scaling data, adding biases, or combining features.

For example, you can add a vector of means to each row of a dataset matrix or multiply each column by a different factor easily with broadcasting.

Key Points

  • Broadcasting lets NumPy perform operations on arrays with different shapes.
  • It stretches smaller arrays virtually without copying data.
  • Shapes must be compatible: dimensions are equal or one is 1.
  • It simplifies code and improves performance by avoiding loops.

Key Takeaways

Broadcasting allows arithmetic between arrays of different shapes by expanding the smaller array.
It works when array dimensions are equal or one dimension is 1, starting from the last dimension.
Broadcasting avoids explicit loops and manual reshaping, making code simpler and faster.
It is widely used in data science for scaling, adding biases, and feature transformations.