Sub topic 11
Keeping or dropping whole groups with filter
This chapter assumes you can build a DataFrame, select columns, and read a basic groupby(...).agg(...) call. It also assumes you know the earlier chapters' point that agg returns one row per group and transform returns one row per original row. filter is the third shape: it returns original rows, but only those that belong to groups that pass a test.
What filter does
filter splits the data into groups, runs a function on each group, and keeps all rows of the groups for which the function returns True. Rows of the other groups are dropped. Nothing is aggregated, so the output has the same columns as the input and a subset of its rows.
Use it when the question is about a group but the answer you want is the rows themselves. Examples are "show me every order from customers with at least five orders" and "keep the regions with more than 15 units sold".
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 in total, which is not more than 15, so both North rows are dropped. South sells 18 units, so all three South rows stay.
The function must return one boolean per group
The function you pass receives each group as a DataFrame. That DataFrame includes the grouping column. The function must return a single value that pandas can treat as a boolean: a Python bool, a NumPy bool_, or something that behaves like one.
A common mistake is to return a per-row result, such as g["units"] > 5. That is a Series, not a scalar. pandas raises a TypeError saying the filter function returned a Series but expected a scalar bool. If you want to test individual rows, filter the DataFrame directly with a boolean mask and skip groupby.
Reduce the group to one value first. Typical reductions are:
g["units"].sum() > 15for a total.len(g) >= 3for the number of rows.g["revenue"].mean() > 80for an average.g["product"].nunique() == 2for a distinct count.(g["revenue"] > 100).any()for "at least one row meets a condition".(g["units"] > 0).all()for "every row meets a condition".
# Keep groups with at least three rows
print(df.groupby("region").filter(lambda g: len(g) >= 3)[["region", "product"]])
# region product
# 2 South A
# 3 South A
# 4 South BFiltering a single column
You can select a column before calling filter. The function then receives a Series for each group, and the result is a Series.
high_avg = df.groupby("region")["revenue"].filter(lambda s: s.mean() > 80)
print(high_avg)
# 0 100.0
# 1 75.0
# Name: revenue, dtype: float64North averages 87.5 and South averages about 73.3, so only the North rows survive. This form is shorter when you only need one column back. When you need the full rows, call filter on the whole GroupBy object.
Index and row order are preserved
filter keeps the original index labels and the original row order. In the first example the result has labels 2, 3, 4, not 0, 1, 2. It is not sorted by group key, and it is not rearranged to put each group's rows together.
This differs from apply, which may add group keys to the index or reorder rows depending on what your function returns. Because filter keeps the index, you can use its output to select or align with the original DataFrame by label.
The dropna parameter
filter has a dropna parameter that defaults to True. With dropna=False, failing groups are not removed. Their rows stay in place and every value is replaced with missing values.
kept = df.groupby("region").filter(lambda g: g["units"].sum() > 15, dropna=False)
print(kept)
# region product units revenue
# 0 NaN NaN NaN NaN
# 1 NaN NaN NaN NaN
# 2 South A 7.0 70.0
# 3 South A 3.0 30.0
# 4 South B 8.0 120.0Note that units became a float column, because integers cannot hold NaN. Use dropna=False only when you need the output to keep the same length and index as the input. In most cases the default is what you want.
Equivalent approach with transform
filter calls your Python function once per group. With many groups this is slow, because each call has Python overhead and builds a sub-DataFrame. If the condition can be expressed with a built-in aggregation, compute it with transform and use the result as a boolean mask.
mask = df.groupby("region")["units"].transform("sum") > 15
print(df[mask][["region", "units"]])
# region units
# 2 South 7
# 3 South 3
# 4 South 8transform("sum") returns a Series aligned with the original rows, where each row holds its group's total. Comparing it to 15 gives one boolean per row, and indexing with it keeps the matching rows. The result is identical to the filter version, and it is usually much faster on data with thousands of groups, because the sum runs in compiled code.
The same idea works for group size. transform("size") gives each row its group's row count, so df[df.groupby("region")["units"].transform("size") >= 3] keeps groups with at least three rows.
Choose between the two like this:
| Situation | Prefer |
|---|---|
| Condition is a built-in aggregation such as sum, mean, size, or nunique | `transform` mask |
| Condition needs custom logic over the group's rows | `filter` with a function |
| Few groups, readability matters most | `filter` |
| Many groups, performance matters | `transform` mask |
Missing group keys
filter follows the same rules as other GroupBy methods for missing keys. Rows whose key is NaN are excluded from grouping by default, so they never form a group. With the default dropna=True in groupby, those rows will not appear in the filtered output either, even if you would have wanted them kept. If you need them, create the GroupBy with groupby(key, dropna=False). The missing keys are then treated as their own group and tested like any other.
Do not confuse the dropna argument of groupby with the dropna argument of filter. The first controls whether rows with missing keys form a group. The second controls whether failing groups are removed or blanked out.
Common errors
- Returning a Series from the function, which raises
TypeError. Reduce the group to one value. - Forgetting that the function returns a boolean for the whole group, not for each row, so a condition like
g["units"] > 5is wrong. - Expecting sorted or grouped output. The original order is kept.
- Expecting one row per group. If that is what you need, use
agg, then filter the summary table with a normal boolean mask. - Using
filteron a large number of groups with a simple condition. Switch to atransformmask.
Exercise
Using the DataFrame from this chapter, write a groupby call that keeps only the rows of regions whose total revenue is at least 200. Which rows are returned, and what are their index labels?
Show answer
Use df.groupby("region").filter(lambda g: g["revenue"].sum() >= 200). North totals 175.0 and South totals 220.0, so only South passes. The result contains the three South rows, with the original index labels 2, 3, and 4. An equivalent faster form is df[df.groupby("region")["revenue"].transform("sum") >= 200].
Exercise
A teammate writes df.groupby("region").filter(lambda g: g["units"] > 5) and gets an error. Why does it fail, and how would you change it to keep regions where every row has more than 2 units?
Show answer
The function returns a boolean Series with one value per row, but filter needs a single boolean per group, so pandas raises a TypeError. Reduce the Series with all(): df.groupby("region").filter(lambda g: (g["units"] > 2).all()). Every row in both regions has more than 2 units, so all five rows are returned.