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.
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.
[[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.