</>
Skip to content
NumPy lessons (24/28)

NumPy — Broadcasting

What is broadcasting?

Automatic expansion of arrays to compatible shapes.

Basic example

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
result = arr + 10  # Adds 10 to each element

Rules

# Rule 1: Arrays with different ndim
a = np.array([1, 2, 3])
b = np.array([[1], [2], [3]])
result = a + b  # (3,) + (3,1) -> (3,3)

Compatible shapes

# Same shape
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + b  # Works

# Scalar
a = np.array([[1, 2], [3, 4]])
c = a + 10  # Works

# Incompatible
a = np.array([1, 2, 3])
b = np.array([1, 2])
# c = a + b  # Error

Practical uses

arr = np.array([[1, 2], [3, 4], [5, 6]])

# Subtract column mean
col_mean = arr.mean(axis=0)
result = arr - col_mean  # Broadcasting

Mini Practice

  1. Practice basic broadcasting
  2. Add scalar to array
  3. Subtract column mean
  4. Test compatible shapes

Up Next

Continue with Functions - Useful functions.

Related Topics

Frequently Asked Questions about Broadcasting

What is Broadcasting in NumPy?

Broadcasting is a fundamental concept in NumPy. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Broadcasting?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Broadcasting.

Why is Broadcasting important in NumPy?

Broadcasting is essential for NumPy development. Understanding this concept will help you write better code and solve real-world problems more effectively.