Thuta Learning
AdvancedData & Databasesintermediate

Broadcasting

Relax. We'll talk through this in plain words — no textbook voice.

Broadcasting is the mechanism NumPy uses to make arrays with different shapes line up according to a set of rules. For example, you can add the same tax rate to every row of a table, or multiply each column by a different scale, without writing a single loop.

python
import numpy as np

# 2 rows x 3 columns
sales = np.array([
    [100, 200, 300],
    [400, 500, 600]
])

# 3 values: one value for each column
bonus = np.array([10, 20, 30])

final_sales = sales + bonus
print(final_sales)

sales has shape (2, 3), and bonus has shape (3,). NumPy applies bonus the same way to each row and adds it column by column.

You should see
[[110 220 330] [410 520 630]]

Info

Broadcasting might look like magic, but it follows a rule: the trailing dimensions have to match, or one of them has to be 1. If neither holds, you get a shape error.

Easy traps

  • If you force together arrays whose shapes don't match, you can get ValueError: operands could not be broadcast together. When you hit that error, print .shape first to see what's going on.

Exercise

If you want to set a different discount rate for each product category, broadcasting lets you apply a column-wise discount across every row.

python
import numpy as np

prices = np.array([
    [1000, 1500, 2000],
    [1200, 1800, 2400]
])

discount_rate = np.array([0.95, 0.90, 0.85])
discounted_prices = prices * discount_rate

print(discounted_prices)

You'll know it worked when: [[ 950. 1350. 1700.] [1140. 1620. 2040.]]

Broadcasting | Thuta Learning