Lesson 3 of 23
❮Prev Next❯

PY-401 · NumPy foundations

Vectorised maths and broadcasting

⏱ 9 min 🐍 Real Python 3 🎬 Animated

3of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

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

    Vectorised maths and broadcasting, running
    1. import numpy as np
    2. prices = np.array([100.0, 250.0, 40.0])
    3. qty = np.array([3, 1, 10])
    4. print(prices * qty) # line totals
    5. print((prices * qty).sum()) # order total
    6. print(prices * 1.18) # every price plus 18% tax
    7. celsius = np.array([0, 25, 100])
    8. print(celsius * 9 / 5 + 32)
    Press ▶ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideaa + b # same shape: value by valueVectorised 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.
    3. 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)

    ▶ Run the example 🎬 Watch it come alive

    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.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. np.array([1, 2, 3]) * 2 gives…
    2. 2. np.array([1, 2]) + np.array([10, 20]) gives…
    3. 3. What is broadcasting?
    4. 4. Shape (3,) times shape (4,) gives…
    5. 5. Why prefer prices * 1.18 to a for loop?

    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 .shape values first.

    Syntax

    a + b       # same shape: value by value
    a * 2       # broadcast one number
    np.round(a, 2)

    Official documentation