Sub topic 11
Keeping or dropping whole groups with filter
This chapter assumes you can build a DataFrame, select columns, and use groupby with sum and agg. You should also know what transform returns, since filter is closely related to it.
What filter does
An aggregation like sum returns one row per group. filter works differently. You give it a function that receives each group as a small DataFrame and returns True or False. Groups that return True are kept in full. Groups that return False are dropped completely.
The result contains original rows, with their original index labels and columns. Nothing is summarized. This makes filter the right tool when the question is "which groups qualify?" and not "what is each group's total?".
A first example
The examples use this DataFrame.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
big_regions = df.groupby("region").filter(lambda g: g["units"].sum() > 15)
print(big_regions[["region", "units"]])
# region units
# 2 South 7
# 3 South 3
# 4 South 8North sells 15 units, which is not more than 15, so the whole North group is removed. South sells 18 units, so all three South rows remain. The kept rows still carry their original index labels 2, 3, and 4.
Rules for the function
The function passed to filter must follow these rules:
- It receives one group as a DataFrame, with all columns.
- It must return a single boolean value for the whole group. Returning a Series of booleans raises an error.
- It can use any logic that reduces a group to one truth value, such as sums, row counts, or
nunique.
A common use is keeping groups with enough rows to be meaningful.
enough_rows = df.groupby("region").filter(lambda g: len(g) >= 3)
print(enough_rows[["region", "product"]])
# region product
# 2 South A
# 3 South A
# 4 South Bfilter versus transform and boolean masks
You can get the same result with transform and a boolean mask. The mask is built from a group-wise value aligned to every row.
mask = df.groupby("region")["units"].transform("sum") > 15
same_result = df[mask]Both approaches return the same rows. The transform version uses a built-in aggregation name, so pandas can run it in optimized code. The filter version calls your Python function once per group. For simple conditions on large data, the mask is usually faster. Use filter when the condition needs logic that a single aggregation cannot express, or when you want the intent to read clearly.
| Goal | Tool | Output |
|---|---|---|
| One summary row per group | `agg` | One row per group |
| Group value on every row | `transform` | Same length as the input |
| Keep or drop whole groups | `filter` | Subset of the original rows |
Common errors
- Returning a non-scalar.
lambda g: g["units"] > 5returns a Series, which causes aTypeError. Reduce it first, for example with.any()or.all(). - Expecting a grouped result.
filterreturns an ordinary DataFrame. There are no group keys in the index, and you can group it again if needed. - Expecting aggregated columns.
filternever changes values. To add a column, combine it withtransformafterward. - Dropping every group. If no group passes, you get an empty DataFrame with the same columns. Check
.emptyif later code assumes data.
Exercise
Using the DataFrame above, write a filter call that keeps only the regions whose total revenue is above 200. Which rows are returned?
Show answer
Use df.groupby("region").filter(lambda g: g["revenue"].sum() > 200). North totals 175.0 and is dropped. South totals 220.0, so rows 2, 3, and 4 are returned with their original index labels.
Exercise
Why does df.groupby("region").filter(lambda g: g["units"] > 5) fail, and how would you change it to keep regions where any row has more than 5 units?
Show answer
The function returns a boolean Series with one value per row, but filter needs one boolean per group. Reduce it with any: lambda g: (g["units"] > 5).any().