Sub topic 6
Filtering rows with boolean masks
This chapter assumes you can create a DataFrame from a dictionary and that pandas is installed and imported as pd. It also assumes you know basic Python comparisons and the difference between a label and a position. The examples reuse the df of five cities built in the first chapter.
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"],
)What a boolean mask is
A boolean mask is a sequence of True and False values with one entry per row. Rows where the mask is True are kept. Rows where it is False are dropped. Filtering in pandas is a two-step process: build a mask, then use it to select rows.
The usual way to build a mask is to compare a column with a value. A comparison on a Series is applied to every element and returns a new Series of dtype bool.
mask = df["population_k"] > 3000
print(mask)
print(mask.dtype)The output is:
a False
b True
c True
d True
e False
Name: population_k, dtype: bool
boolThe mask keeps the same index as df. That detail matters later, because pandas uses the labels to line the mask up with the rows.
Applying a mask
Pass the mask inside square brackets, or to .loc.
print(df[mask])
print(df.loc[mask])Both calls return rows b, c, and d. The result is a new DataFrame, and the surviving rows keep their original labels. Row b is still called b, not 0.
The two forms differ in what else you can do. .loc takes a second argument for columns, so you can filter rows and choose columns in one step.
print(df.loc[mask, ["city", "population_k"]])Prefer .loc when you also need to pick columns, and when you assign values (see the chapter on assignment). Plain brackets are fine for a quick row filter.
The whole process looks like this.
Working with the mask itself
A mask is an ordinary Series, so you can inspect it. True counts as 1 and False as 0 in arithmetic. That gives you cheap answers without building the filtered frame.
print(mask.sum()) # how many rows match: 3
print(mask.mean()) # fraction of rows that match: 0.6
print(mask.any()) # is there at least one match: True
print(mask.all()) # do all rows match: FalseGiving a mask a name is also good style. Compare these two lines:
df[df["population_k"] > 3000] # fine for one condition
big = df["population_k"] > 3000 # a named mask reads better and can be reused
print(df[big])
print(df[~big])The second form lets you reuse big, test it with .sum(), and combine it with other masks. Combining masks has its own chapter, but note that ~big inverts a mask, so df[~big] returns the rows that did not match.
Other kinds of comparisons
Any expression that yields one boolean per row works as a mask.
print(df[df["continent"] == "South America"]) # equality
print(df[df["country"] != "Peru"]) # inequality
print(df[df["population_k"] <= 2800]) # inclusive upper boundYou can also compare two columns with each other, as long as the comparison is element by element:
df2 = pd.DataFrame({"low": [1, 5, 3], "high": [2, 4, 6]})
print(df2[df2["low"] < df2["high"]])Only rows 0 and 2 survive, because row 1 has low greater than high.
Masks can come from several sources
The mask does not have to come from a comparison. These all work:
- A boolean Series, as above.
- A NumPy boolean array, for example
mask.to_numpy(). - A plain Python list of booleans with exactly one entry per row.
- A function passed to
.loc, called with the DataFrame and returning a mask.
print(df[mask.to_numpy()])
print(df[[True, False, True, False, True]])
print(df.loc[lambda d: d["population_k"] > 3000])The function form is useful in a method chain, where the intermediate DataFrame has no name. The lambda receives that intermediate result as d.
A NumPy array or list is matched by position, so the first value applies to the first row. A Series is matched by label. This distinction explains the errors in the next section.
Common errors
Using `and`, `or`, or `not`
Python's and asks whether a whole Series is true, which is ambiguous. pandas raises an error.
a = df["population_k"] > 3000
b = df["continent"] == "South America"
try:
df[a and b]
except ValueError as exc:
print(exc)The message begins "The truth value of a Series is ambiguous". The fix is to use the element-wise operators &, |, and ~, with each comparison in its own variable or its own parentheses. The next chapter covers this in detail.
A mask of the wrong length
A list or array mask must have one entry per row. Otherwise pandas cannot decide which rows to keep.
try:
df[[True, False]]
except ValueError as exc:
print(exc)This prints "Item wrong length 2 instead of 5."
A Series mask with a different index
A boolean Series is aligned to the DataFrame by label. If the labels do not line up, pandas cannot align it and raises an error.
other = df.reset_index(drop=True) # index becomes 0..4
foreign_mask = other["population_k"] > 3000
try:
df[foreign_mask]
except Exception as exc:
print(type(exc).__name__)This prints IndexingError. The mask has labels 0 to 4, while df has labels a to e. This mistake often appears after a reset_index, a merge, or a sort_values on one frame while the mask comes from another. If you really want position-based matching, convert the mask first with foreign_mask.to_numpy().
If the mask has the same labels in a different order, pandas reorders it to match, so the result is still correct.
Missing values quietly drop out
Comparisons with a missing value (NaN) return False. A row whose value is missing therefore never passes > 3000, and it never passes <= 3000 either. Filtering with the condition and its opposite can leave some rows in neither group. The chapter on missing values shows how to handle them on purpose.
Edge cases
- No matches. If no row passes, you get an empty DataFrame with the same columns, not an error. Check
mask.any()orlen(result)when an empty result would be a problem. - All rows match. You get a copy of every row. It is a new object, not the original.
- The result is a new object. The filtered frame has its own row selection, but writing into it is a separate topic. See the chapter on assignment and copies before you modify a filtered result.
- Index duplicates. If the index has repeated labels, a boolean mask still works, because it is aligned when the index is identical to the frame's own. Label-based lookups with
.loc[label]may return several rows in that case. - Column masks.
.localso accepts a boolean array in the column position, for exampledf.loc[:, df.dtypes == "int64"]. The mask then has one entry per column.
Summary of the working model
- A comparison on a column returns a boolean Series with the same index.
df[mask]anddf.loc[mask]keep the rows where the mask isTrue, and the original labels stay.- Series masks are aligned by label, and arrays and lists are matched by position.
- Use
&,|, and~, notand,or, andnot. mask.sum()andmask.mean()count and measure matches without creating a new frame.
Exercise
Using the df above, write code that returns only the city and country columns for rows where population_k is below 3000. Then say how many rows it returns, and what happens to the row labels.
Show answer
Use small = df["population_k"] < 3000 and then df.loc[small, ["city", "country"]]. Two rows match, Oslo (709) and Quito (2800). The labels a and e are kept, so the result is not renumbered to 0 and 1. small.sum() returns 2.
Exercise
You build m = other["population_k"] > 3000 from a copy of df that was created with reset_index(drop=True). Why does df[m] raise an IndexingError, and how do you get the filter to work?
Show answer
A boolean Series is aligned by label. m has labels 0 to 4, but df has labels a to e, so no labels match. Either build the mask from df itself, or drop the labels with df[m.to_numpy()], which matches by position. The second option is correct only when both frames have the rows in the same order.