Sub topic 6
Filtering rows with boolean masks
This chapter assumes you can build a DataFrame from a dictionary, select columns with brackets, and read basic .loc syntax. It uses the df of five cities from the earlier chapters.
What a boolean mask is
A boolean mask is a Series of True and False values with the same index as the DataFrame. Each value says whether the row at that label should be kept. When you pass a mask inside brackets, pandas returns only the rows where the mask is True.
You build a mask by comparing a column to a value. The comparison runs on every element at once, so you don't need a loop.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)
mask = df["population_k"] > 3000
print(mask)
print(df[mask])The first print shows a boolean Series indexed by a to e. It is False for Oslo, True for Lima, True for Pune, True for Cairo and False for Quito. The second print shows the three rows marked True.
How the filter works
The steps below show what happens when you write df[mask].
pandas lines up the mask with the rows by index label, not by position. For a mask built from the same DataFrame this is invisible, because the labels already match.
Combining conditions
Real filters usually need more than one test. Combine masks with & (and), | (or), and ~ (not). These operators work element by element.
big = df["population_k"] > 3000
south_america = df["continent"] == "South America"
print(df[big & south_america])
print(df[big | south_america])
print(df[~big])The three results are:
big & south_americakeeps rows where both are true. Only Lima qualifies.big | south_americakeeps rows where at least one is true. This gives Lima, Pune, Cairo and Quito.~bigflips every value, so it keeps the cities with 3000 thousand people or fewer: Oslo and Quito.
Parentheses matter
The operators & and | bind more tightly than comparisons such as > and ==. If you write a condition inline, wrap each comparison in parentheses.
# Correct: each comparison has its own parentheses
print(df[(df["population_k"] > 3000) & (df["continent"] == "South America")])
# Raises an error: Python reads this as 3000 & df["continent"]
# print(df[df["population_k"] > 3000 & df["continent"] == "South America"])Naming each mask as a variable, as in the earlier example, avoids the problem. It also makes long conditions easier to read.
Masks with .loc
A mask also works inside .loc, as the row selector. This is the form you need when you also want to choose columns, or when you assign values later.
print(df.loc[big & south_america, ["city", "population_k"]])This returns the rows that pass the filter and only the two named columns.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ValueError: The truth value of a Series is ambiguous` | Used `and`, `or`, or `not` | Use `&`, `\ | `, or `~` |
| Wrong rows or a `TypeError` with an inline condition | Missing parentheses | Wrap each comparison in parentheses, or name each mask | |
| `IndexingError: Unalignable boolean Series` | The mask index does not match the DataFrame | Build the mask from the same DataFrame, or use `.values` on a mask of the right length |
Exercise
Using the df above, write one line that returns the cities that are not in Europe and have a population under 5000 thousand. Which cities does it return?
Show answer
df[(df["continent"] != "Europe") & (df["population_k"] < 5000)]. It returns Pune (3124) and Quito (2800). Oslo is excluded because it is in Europe, and Lima and Cairo are excluded because their populations are over 5000. You could also write ~(df["continent"] == "Europe") for the first condition.