Sub topic 7
Filtering rows with boolean masks
This chapter assumes you can select with [] and loc and know that a DataFrame column is a Series.
What a mask is
A comparison on a Series returns a Series of True and False values with the same index. This is a boolean mask. Passing a mask to df[...] or df.loc[...] keeps the rows where the mask is True.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
mask = df["pop_m"] > 3
print(mask.tolist()) # [False, True, True, False]
print(df[mask]) # the Lima and Pune rowsCombining conditions
Use & for and, | for or, and ~ for not. Wrap each comparison in parentheses, because these operators bind more tightly than > and ==.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
eu_mid = df[(df["pop_m"] > 1) & (df["region"] == "EU")]
print(eu_mid) # only Rome
not_eu = df[~(df["region"] == "EU")]
print(not_eu["city"].tolist()) # ['Lima', 'Pune']Python's and, or, and not do not work here. They ask whether a whole Series is true, and pandas raises ValueError: The truth value of a Series is ambiguous.
Helpers for common tests
Two methods replace long chains of conditions:
isin(values)isTruewhere the value appears in a list.between(left, right)isTruefor values in a range, including both ends by default.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
print(df[df["region"].isin(["EU", "AS"])]["city"].tolist())
# ['Oslo', 'Pune', 'Rome']
print(df[df["pop_m"].between(1, 5)]["city"].tolist())
# ['Pune', 'Rome']Masks with loc
df[mask] returns all columns. To filter rows and pick columns in one step, use loc with the mask first:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
print(df.loc[df["pop_m"] > 3, ["city", "pop_m"]])Prefer this form when you assign values, such as df.loc[mask, "col"] = 0. It avoids chained-assignment problems, which a later chapter covers.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ValueError: truth value ... ambiguous` | Used `and`, `or`, or `not` | Use `&`, `\ | `, `~` |
| Wrong result or a `TypeError` | Missing parentheses around comparisons | Wrap each comparison | |
| Mask length error | Mask built from a different frame | Build it from the frame you filter |
Exercise
Using the df above, write one expression that returns the cities that are not in the EU and have a population over 3 million. What does it return?
Show answer
df.loc[(df["region"] != "EU") & (df["pop_m"] > 3), "city"] returns Lima and Pune. Both are outside the EU and have populations above 3 million (10.7 and 3.1).