GroupBy transform() and filter()
An aggregation like groupby().sum() returns one row per group. Often you instead want to keep every original row and attach a group-level value to it ("this order's share of its customer's total"), or keep only the groups that satisfy some condition. That's what transform() and filter() are for.
| Method | Returns | Use for |
|---|---|---|
agg() / sum() … |
one row per group | summaries |
transform() |
same shape as the input | group values on every row, normalising, filling |
filter() |
the original rows of the groups that pass a test | dropping whole groups |
apply() |
anything | custom per-group logic |
transform(): a group value on every row
import pandas as pd
orders = pd.DataFrame({
"customer": ["ann", "bob", "ann", "cat", "bob", "ann"],
"amount": [40, 25, 60, 90, 75, 100],
})
orders["customer_total"] = orders.groupby("customer")["amount"].transform("sum")
orders["share"] = (orders["amount"] / orders["customer_total"]).round(2)
print(orders) customer amount customer_total share
0 ann 40 200 0.20
1 bob 25 100 0.25
2 ann 60 200 0.30
3 cat 90 90 1.00
4 bob 75 100 0.75
5 ann 100 200 0.50
transform("sum") computed each customer's total and broadcast it back to every one of that customer's rows, so the result lines up with the original frame and can be stored as a new column.
Comparing rows with their group
A common use is to compare each value with its group's average:
import pandas as pd
temps = pd.DataFrame({
"city": ["Oslo", "Oslo", "Oslo", "Rome", "Rome", "Rome"],
"month": ["Jun", "Jul", "Aug", "Jun", "Jul", "Aug"],
"temp": [15.2, 17.8, 16.4, 23.1, 26.0, 25.6],
})
group_mean = temps.groupby("city")["temp"].transform("mean")
temps["vs_city_avg"] = (temps["temp"] - group_mean).round(2)
temps["warmest"] = temps["temp"] == temps.groupby("city")["temp"].transform("max")
print(temps) city month temp vs_city_avg warmest
0 Oslo Jun 15.2 -1.27 False
1 Oslo Jul 17.8 1.33 True
2 Oslo Aug 16.4 -0.07 False
3 Rome Jun 23.1 -1.80 False
4 Rome Jul 26.0 1.10 True
5 Rome Aug 25.6 0.70 False
Filling missing values per group
transform with a function lets you fill gaps with a value from the same group rather than the whole column, which is usually more accurate:
import numpy as np
import pandas as pd
rents = pd.DataFrame({
"district": ["Centre", "Centre", "Centre", "Suburb", "Suburb", "Suburb"],
"rent": [1450, np.nan, 1550, 820, 780, np.nan],
})
rents["filled"] = rents.groupby("district")["rent"].transform(lambda s: s.fillna(s.median()))
print(rents) district rent filled
0 Centre 1450.0 1450.0
1 Centre NaN 1500.0
2 Centre 1550.0 1550.0
3 Suburb 820.0 820.0
4 Suburb 780.0 780.0
5 Suburb NaN 800.0
A missing Centre rent was filled with the Centre median (1500), not with the overall median, which the cheaper Suburb flats would drag down.
Ranking and numbering within groups
cumcount(), rank() and cumsum() also work per group and keep the original shape:
import pandas as pd
scores = pd.DataFrame({
"team": ["red", "blue", "red", "blue", "red"],
"player": ["Ari", "Bo", "Cas", "Dia", "Eli"],
"points": [12, 30, 25, 18, 25],
})
scores["nth_in_team"] = scores.groupby("team").cumcount() + 1
scores["team_rank"] = scores.groupby("team")["points"].rank(ascending=False, method="min").astype(int)
scores["running_total"] = scores.groupby("team")["points"].cumsum()
print(scores) team player points nth_in_team team_rank running_total
0 red Ari 12 1 3 12
1 blue Bo 30 1 1 30
2 red Cas 25 2 1 37
3 blue Dia 18 2 2 48
4 red Eli 25 3 1 62
filter(): keep or drop whole groups
filter() calls a function with each group's DataFrame. Groups for which it returns True are kept (all their rows); the rest disappear:
import pandas as pd
orders = pd.DataFrame({
"customer": ["ann", "bob", "ann", "cat", "bob", "ann"],
"amount": [40, 25, 60, 90, 75, 100],
})
repeat = orders.groupby("customer").filter(lambda g: len(g) >= 2)
print(repeat)
big_spenders = orders.groupby("customer").filter(lambda g: g["amount"].sum() > 100)
print(big_spenders["customer"].unique()) customer amount
0 ann 40
1 bob 25
2 ann 60
4 bob 75
5 ann 100
['ann']
Cat placed only one order, so she's missing from repeat; Bob spent exactly 100, which is not more than 100.
Tip:
filtergives the same result as atransformmask:orders[orders.groupby("customer")["amount"].transform("size") >= 2]. The mask version is often faster on big data.
Test yourself
How many rows does df.groupby("g")["x"].transform("mean") return?
- One per group
- The same number as df
- One
- It depends on the data
Which keeps only the rows of groups that have at least 3 rows?
- df.groupby("g").filter(lambda g: len(g) >= 3)
- df.groupby("g").size() >= 3
- df.groupby("g").head(3)
- df.groupby("g").agg(len) >= 3
Why fill missing prices with the median of their own category rather than the overall median?
- It is faster
- Values within a group are usually more similar, so the estimate is closer
- pandas requires it
- The overall median ignores NaN