Most questions you ask of data are conditions: which days were hotter than 35°C? Which students failed? Which prices are missing? In NumPy you answer them with boolean indexing: write the condition, and use the result to pick out the matching values. No loops needed.
This lesson shows how boolean indexing works, how to combine conditions, how to count and change matching values, and how np.where replaces values or finds their positions.
A condition gives an array of True and False
Compare an array with a value and NumPy checks every element, returning a boolean array (also called a mask) of the same shape:
import numpy as np
temps = np.array([31, 36, 35, 38, 30, 29, 37])
hot = temps > 35
print(hot) # [False True False True False False True]
Use the mask to filter
Put the mask inside square brackets and you get only the values where it's True:
print(temps[hot]) # [36 38 37]
print(temps[temps > 35]) # the same, in one line
The result is always a 1D copy containing just the matching values. The original array is unchanged.
Combining conditions with & and |
Use & for "and", | for "or" and ~ for "not". Put brackets around each condition, because & and | are evaluated before > and <:
print(temps[(temps > 30) & (temps < 36)]) # [31 35]
print(temps[(temps < 30) | (temps > 37)]) # [38 29]
print(temps[~(temps > 35)]) # [31 35 30 29]
Two common errors:
- Writing
temps > 30 & temps < 36without brackets gives a confusingValueError. - Writing
andororinstead of&or|givesValueError: The truth value of an array with more than one element is ambiguous. Python'sandwants a single True or False, but an array holds many.
Counting and checking matches
True counts as 1 and False as 0, so summing a mask counts the matches, and the mean gives the fraction:
print((temps > 35).sum()) # 3 hot days
print((temps > 35).mean()) # 0.428... so 43% of days
print((temps > 40).any()) # False: was any day above 40?
print((temps > 25).all()) # True: were all days above 25?
Changing values that match
Assign to a boolean index to change only the matching values. This is a quick way to clean data, for example capping outliers:
marks = np.array([45, 102, 78, -3, 66])
marks[marks > 100] = 100 # cap at 100
marks[marks < 0] = 0 # no negative marks
print(marks) # [ 45 100 78 0 66]
np.clip(marks, 0, 100) does the same capping in one call.
Boolean indexing on 2D arrays
Masks work on tables too. A common pattern is to filter rows based on one column:
# columns: age, monthly spend (₹)
customers = np.array([
[22, 1500],
[35, 4200],
[41, 800],
[29, 3100],
])
big_spenders = customers[customers[:, 1] > 3000]
print(big_spenders)
[[ 35 4200]
[ 29 3100]]
customers[:, 1] > 3000 makes a mask with one value per row, and using it as the row index keeps the whole matching rows. This is exactly what pandas does under the hood when you filter a DataFrame.
np.where: choose between two values
np.where(condition, x, y) builds a new array: where the condition is true it takes x, otherwise y. It's an "if-else" for every element at once:
marks = np.array([45, 82, 30, 67, 91])
result = np.where(marks >= 40, "pass", "fail")
print(result) # ['pass' 'pass' 'fail' 'pass' 'pass']
x and y can be arrays too. Here we give a 10% discount on orders above ₹1,000 only:
orders = np.array([500, 1200, 2500, 800])
to_pay = np.where(orders > 1000, orders * 0.9, orders)
print(to_pay) # [ 500. 1080. 2250. 800.]
For more than two choices, use np.select:
grades = np.select(
[marks >= 80, marks >= 60, marks >= 40],
["A", "B", "C"],
default="F",
)
print(grades) # ['C' 'A' 'F' 'B' 'A']
The first condition that matches wins, so order them from strictest to loosest.
np.where with one argument: find positions
Called with only a condition, np.where returns the positions where it's true:
print(np.where(marks < 50)) # (array([0, 2]),)
print(np.where(marks < 50)[0]) # [0 2]
It returns a tuple with one array per dimension, which is why you take [0] for a 1D array. np.argwhere and np.flatnonzero are alternatives you may see.
Filtering out missing values
Missing numbers in NumPy are stored as np.nan. You can't find them with == np.nan (NaN isn't equal even to itself), so use np.isnan:
rain = np.array([12.0, np.nan, 3.5, np.nan, 8.0])
print(np.isnan(rain).sum()) # 2 missing
print(rain[~np.isnan(rain)]) # [12. 3.5 8. ]
Practice
- From
np.arange(1, 21), keep only the numbers divisible by 3.
Show the answer
n = np.arange(1, 21)
print(n[n % 3 == 0]) # [ 3 6 9 12 15 18]
- In
prices = np.array([120, 45, 300, 80, 150]), how many prices are between 50 and 200, inclusive?
Show the answer
prices = np.array([120, 45, 300, 80, 150])
print(((prices >= 50) & (prices <= 200)).sum()) # 3
- Replace every negative number in
np.array([3, -1, 4, -5, 9])with 0, without changing the original array.
Show the answer
a = np.array([3, -1, 4, -5, 9])
print(np.where(a < 0, 0, a)) # [3 0 4 0 9]
np.where returns a new array; a[a < 0] = 0 would change a itself.
Interview questions
What is boolean indexing in NumPy?
Indexing an array with a boolean array of the same shape. It returns a new 1D array of the elements where the mask is True. It's the standard way to filter data by condition without a loop.
Why do you need & instead of "and" with NumPy arrays?
and asks for a single truth value of each side, and an array with several elements has no single truth value, so Python raises a ValueError. & works element by element. Because & binds more tightly than comparisons, each condition needs brackets.
What does np.where return?
With three arguments, an array that takes values from x where the condition is true and from y elsewhere. With one argument, a tuple of index arrays, one per dimension, giving the positions where the condition is true.
What to learn next
- Change an array's shape with reshape, flatten and transpose.
- See the same filtering ideas on labelled data in the pandas DataFrame tutorial.