PY-401 ยท NumPy foundations
Filtering with boolean masks
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก 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.
import numpy as nptemps = np.array([28, 35, 31, 38, 26, 33])hot = temps > 32print(hot)print(temps[hot])print(hot.sum(), "hot days")print(temps[(temps > 27) & (temps < 34)])print(np.where(temps > 32, "hot", "ok"))
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
[False True False True False True]
[35 38 33]
3 hot days
[28 31 33]
['ok' 'hot' 'ok' 'hot' 'ok' 'hot'] ๐ฏ Keep only the orders worth 500 or more in an array called big, then print how many there are.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
big = orders[orders >= 500] then print(len(big))
- 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.
- The Python idea
mask = a > 10A boolean mask is an array of True and False made by a condition, such astemps > 32. - 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") Real-world scenario
A bank flags card payments with amounts[(amounts > 5000) & (country != home)] and sends only those for a fraud check.
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: Aggregations and axes โ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|, notandandor, 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
- Boolean array indexing (docs.python.org)