PY-401 · NumPy foundations
Vectorised maths and broadcasting
⏱ 9 min 🐍 Real Python 3 🎬 Animated ✓ Completed
⚡ The 30-second answer
Vectorised maths means writing an operation once and NumPy applies it to every value: prices * qty multiplies matching pairs, and prices * 1.18 multiplies every price by 1.18. Stretching a single number (or a smaller array) to fit a bigger one is called broadcasting. It replaces most for loops in data work and runs far faster.
- Do maths on two arrays of the same shape
- Apply one number to every value
- Replace a for loop with one expression
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import numpy as npprices = np.array([100.0, 250.0, 40.0])qty = np.array([3, 1, 10])print(prices * qty) # line totalsprint((prices * qty).sum()) # order totalprint(prices * 1.18) # every price plus 18% taxcelsius = np.array([0, 25, 100])print(celsius * 9 / 5 + 32)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
[300. 250. 400.]
950.0
[118. 295. 47.2]
[ 32. 77. 212.] 🎯 Convert the race distances in km to miles (1 km = 0.621371 miles), rounded to 2 decimal places, into an array called miles. No for loop.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
miles = np.round(km * 0.621371, 2)
- The problemFinance wants every price in the catalogue with 18% tax added, and a line total for each order. In plain Python that is two loops. In NumPy it is two short lines.
- The Python idea
a + b # same shape: value by valueVectorised maths means writing an operation once and NumPy applies it to every value:prices * qtymultiplies matching pairs, andprices * 1.18multiplies every price by 1.18. - In real lifeA weather service turns a whole day of sensor readings from Kelvin to Celsius with one line,
readings - 273.15, for thousands of stations at once.
Start with a question
Finance wants every price in the catalogue with 18% tax added, and a line total for each order. In plain Python that is two loops. In NumPy it is two short lines.
Shorter code, fewer bugs and 10 to 100 times the speed. Every pandas column calculation you will write is vectorised maths.
Explain it like I'm 10
Imagine a row of cups and a magic jug. Pour once and every cup fills at the same time. That is a vectorised operation: one pour, all cups.
The technical explanation
a + b, a * b, a / b and a ** 2 work value by value when the arrays have the same shape.
With a single number, a * 1.18, NumPy broadcasts the number to every position.
Broadcasting also works between a 2-D table and one row: each row of the table is combined with that row.
Functions such as np.round, np.sqrt and np.abs also run on the whole array.
Syntax
a + b # same shape: value by value
a * 2 # broadcast one number
np.round(a, 2) Real-world scenario
A weather service turns a whole day of sensor readings from Kelvin to Celsius with one line, readings - 273.15, for thousands of stations at once.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
🏆 Every lesson counts toward your certificate Next: Filtering with boolean masks →Questions people ask
What does vectorised mean in NumPy?
It means one expression works on every value of an array, such as prices * 1.18. The loop still happens, but inside NumPy's compiled code instead of a Python for loop, so it is much faster.
What are the broadcasting rules in NumPy?
NumPy compares shapes from the right. Two dimensions fit if they are equal or one of them is 1. A single number fits any shape. If any pair does not fit, you get "operands could not be broadcast together".
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What does vectorised mean in NumPy?
It means one expression works on every value of an array, such as prices * 1.18. The loop still happens, but inside NumPy's compiled code instead of a Python for loop, so it is much faster.
beginner What are the broadcasting rules in NumPy?
NumPy compares shapes from the right. Two dimensions fit if they are equal or one of them is 1. A single number fits any shape. If any pair does not fit, you get "operands could not be broadcast together".
intermediate np.array([1, 2, 3]) * 2 gives…
[2 4 6]. The 2 is broadcast to every value. (A list * 2 would repeat the list.)
intermediate np.array([1, 2]) + np.array([10, 20]) gives…
[11 22]. Same shape, so values are added pair by pair.
Quick revision
Remember
- Do maths on two arrays of the same shape
- Apply one number to every value
- Replace a for loop with one expression
- Arrays must line up. A shape (3,) array times a shape (4,) array raises "operands could not be broadcast together". Print both
.shapevalues first.
Syntax
a + b # same shape: value by value
a * 2 # broadcast one number
np.round(a, 2) Official documentation
- Broadcasting (docs.python.org)