Sub topic 7
Filtering rows with boolean masks
This chapter assumes you can create a DataFrame, know what the Index is, and have seen loc and iloc for selection. It builds on those to show how to choose rows by condition. You will learn how a mask is built, how to combine conditions, and which errors come up most often.
What a boolean mask is
A boolean mask is a Series of True and False values with the same Index as the data. Comparing a column to a value produces one. Each row gets True if it meets the condition.
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)
print(mask.dtype)The output shows False, True, True, False with the labels 0 to 3, and the dtype is bool. The comparison is vectorized, so no Python loop runs.
Passing the mask to [] or loc keeps only the rows where it is True.
print(df[mask])
print(df.loc[mask])Both lines return the rows for Lima and Pune. Most code writes the condition inline: df[df["pop_m"] > 3].
Selecting rows and columns together
loc accepts a row selector and a column selector in one call. This is the preferred form when you also want to pick columns.
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"],
})
big = df.loc[df["pop_m"] > 3, ["city", "pop_m"]]
print(big)The mask picks rows and the list of labels picks columns. The result keeps the original Index labels (1 and 2), because filtering never renumbers rows.
How a mask is applied
The diagram shows the steps pandas performs for a filter.
pandas matches the mask to the rows by Index label, not only by position. A mask built from the same DataFrame always lines up. A mask built from a different object can behave differently, as the edge cases below show.
Combining conditions
Python's and, or, and not do not work on Series. They try to turn a whole Series into a single truth value, which raises an error. Use the element-wise operators instead.
| Meaning | Operator | Column |
|---|---|---|
| and | `&` | |
| or | `\ | ` |
| not | `~` |
Each comparison must be wrapped in parentheses, because & and | bind more tightly than > or ==.
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_small = df[(df["region"] == "EU") & (df["pop_m"] < 1)]
print(eu_small)
not_eu = df[~(df["region"] == "EU")]
print(not_eu)
either = df[(df["region"] == "SA") | (df["region"] == "AS")]
print(either)The first filter returns Oslo. The second returns Lima and Pune. The third also returns Lima and Pune.
If you see ValueError: The truth value of a Series is ambiguous, you used and, or, not, or an if on a Series. Replace them with &, |, ~, or reduce the Series with .any() or .all().
Helpful mask methods
Some conditions are awkward as comparisons. pandas has methods that return masks.
| Method | Returns True when |
|---|---|
| `s.isin(values)` | the value is in the given list |
| `s.between(a, b)` | the value is from a to b, inclusive by default |
| `s.isna()` | the value is missing |
| `s.notna()` | the value is not missing |
| `s.str.contains(text)` | the string contains the text |
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(["SA", "AS"])])
print(df[df["pop_m"].between(2, 5)])
print(df[df["city"].str.contains("o")])The isin call replaces a chain of | comparisons. between(2, 5) returns Pune and Rome. str.contains("o") is case sensitive. It matches Oslo and Rome, but not Lima or Pune. If a string column holds missing values, str.contains returns NaN for them, and using that as a mask fails. Pass na=False to treat them as non-matches.
Using query for readable filters
DataFrame.query takes the condition as a string. Inside it, you write column names directly and use and, or, and not.
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"],
})
limit = 3
print(df.query("pop_m > @limit and region != 'EU'"))The @ prefix refers to a Python variable. query is handy for long conditions. Its drawbacks are that editors cannot check the string, and column names with spaces need backticks.
Edge cases
Masks and missing values
A comparison with NaN is False, so rows with missing values drop out of > and == filters. They also drop out of != filters in the opposite direction: NaN != "EU" is True, so those rows are kept.
import pandas as pd
s = pd.Series([1.0, None, 3.0])
print((s > 2).tolist()) # [False, False, True]
print((s != 3).tolist()) # [True, True, False]If missing rows matter, add an explicit isna() or notna() condition.
Mask alignment
When you use a boolean Series as a mask, pandas checks its Index against the data. If the Index differs, df[mask] can raise an IndexingError ("Unalignable boolean Series provided as indexer"). A plain list of booleans has no labels, so it must match the length of the data.
import pandas as pd
df = pd.DataFrame({"x": [1, 2, 3]})
print(df[[True, False, True]]) # rows 0 and 2Counting and testing masks
Because True counts as 1, you can summarize a mask directly.
import pandas as pd
df = pd.DataFrame({"pop_m": [0.7, 10.7, 3.1, 2.8]})
mask = df["pop_m"] > 3
print(mask.sum()) # 2 rows match
print(mask.mean()) # 0.5, the share of matching rows
print(mask.any(), mask.all()) # True FalseFiltering returns a new object
df[mask] returns a new DataFrame. Assigning into it later may trigger a SettingWithCopyWarning. If you plan to modify the result, call .copy() first. Chapter material on copies covers this in detail.
import pandas as pd
df = pd.DataFrame({"pop_m": [0.7, 10.7, 3.1, 2.8]})
big = df[df["pop_m"] > 3].copy()
big["flag"] = True
print(big)Setting values with a mask
A mask can also be used on the left side of an assignment. Use a single loc call for this.
import pandas as pd
df = pd.DataFrame({"pop_m": [0.7, 10.7, 3.1, 2.8]})
df.loc[df["pop_m"] > 3, "size"] = "large"
df.loc[df["pop_m"] <= 3, "size"] = "small"
print(df)The column size is created on the first line, with NaN for unmatched rows, and filled by the second line.
Common errors
- Using
andororinstead of&and|, which raises "truth value of a Series is ambiguous". - Forgetting parentheses around each comparison.
- Writing
df[df["a"] > 1]["b"] = 0, a chained assignment that may not changedf. Usedf.loc[df["a"] > 1, "b"] = 0. - Expecting the Index to restart at 0 after filtering. Use
reset_index(drop=True)if you need that. - Using
== Noneor== np.nanto find missing values. Useisna().
Exercise
Given the DataFrame with columns city, popm, and region from this chapter, write one expression that returns the city names of EU rows with popm above 1. Which Index labels does the result have?
Show answer
Use df.loc[(df["region"] == "EU") & (df["pop_m"] > 1), "city"]. Only Rome matches, so the result is a Series with the single value "Rome" and the Index label 3, because filtering keeps the original labels.
Exercise
A Series s = pd.Series([1.0, None, 3.0]) is filtered with s[s != 3]. How many rows come back, and why?
Show answer
Two rows come back, the values 1.0 and NaN. The comparison NaN != 3 evaluates to True, so the missing row is kept. Add & s.notna() to exclude it.