Lesson 4 of 23
โฎPrev Nextโฏ

PY-401 ยท NumPy foundations

Filtering with boolean masks

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

4of 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

    A boolean mask is an array of True and False made by a condition, such as temps > 32. Putting the mask inside square brackets, temps[temps > 32], keeps only the values where the mask is True. Combine conditions with & (and) and | (or), each wrapped in brackets.

    • Build a mask with a condition
    • Filter values with the mask
    • Combine conditions with & and |

    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.

    Filtering with boolean masks, running
    1. import numpy as np
    2. temps = np.array([28, 35, 31, 38, 26, 33])
    3. hot = temps > 32
    4. print(hot)
    5. print(temps[hot])
    6. print(hot.sum(), "hot days")
    7. print(temps[(temps > 27) & (temps < 34)])
    8. print(np.where(temps > 32, "hot", "ok"))
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemThe operations team asks: "On which days was it above 32ยฐC, and how many?" With a mask, that is one line for the days and one for the count.
    2. The Python ideamask = a > 10A boolean mask is an array of True and False made by a condition, such as temps > 32.
    3. In real lifeA bank flags card payments with amounts[(amounts > 5000) & (country != home)] and sends only those for a fraud check.

    Start with a question

    The operations team asks: "On which days was it above 32ยฐC, and how many?" With a mask, that is one line for the days and one for the count.

    Filtering is the most common question in data work: which customers, which orders, which days. pandas filters rows the same way.

    Explain it like I'm 10

    A mask is a stencil. You hold it over the numbers, and only the ones under the holes (the True spots) show through.

    The technical explanation

    temps > 32 compares every value and returns an array of booleans with the same shape.

    temps[mask] keeps the values where the mask is True and drops the rest.

    True counts as 1, so mask.sum() counts the matches.

    np.where(condition, if_true, if_false) builds a new array by choosing per value, for labels such as "hot" and "ok".

    Syntax

    mask = a > 10
    a[mask]
    a[(a > 10) & (a < 20)]
    np.where(a > 10, "big", "small")

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    A bank flags card payments with amounts[(amounts > 5000) & (country != home)] and sends only those for a fraud check.

    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. a = np.array([1, 5, 9]). What is a > 4?
    2. 2. What does a[a > 4] return for a = [1, 5, 9]?
    3. 3. Which correctly means "between 2 and 8"?
    4. 4. How do you count the True values in a mask?
    5. 5. np.where(a > 0, "pos", "neg") returnsโ€ฆ

    Questions people ask

    Why does "and" not work with NumPy arrays?

    and asks for one True or False for the whole array, which NumPy refuses because it is ambiguous. & combines two masks value by value. Wrap each condition in brackets because & binds tighter than >.

    How do I find the positions where a condition is true in NumPy?

    Use np.where(condition) with one argument, or np.flatnonzero(condition) for a 1-D array. Both return the indexes of the True values.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Why does "and" not work with NumPy arrays?

    and asks for one True or False for the whole array, which NumPy refuses because it is ambiguous. & combines two masks value by value. Wrap each condition in brackets because & binds tighter than >.

    beginner How do I find the positions where a condition is true in NumPy?

    Use np.where(condition) with one argument, or np.flatnonzero(condition) for a 1-D array. Both return the indexes of the True values.

    intermediate a = np.array([1, 5, 9]). What is a > 4?

    [False True True]. A comparison gives one True/False per value.

    intermediate What does a[a > 4] return for a = [1, 5, 9]?

    [5 9]. The mask keeps only the True positions.

    Quick revision

    Remember

    • Build a mask with a condition
    • Filter values with the mask
    • Combine conditions with & and |
    • Use & and |, not and and or, and put brackets around each condition: (a > 1) & (a < 5). Without brackets Python reads it in the wrong order.

    Syntax

    mask = a > 10
    a[mask]
    a[(a > 10) & (a < 20)]
    np.where(a > 10, "big", "small")

    Official documentation