GroupBy
16 min
groupby is pandas' answer to "for each department, what's the total
salary?" — the split-apply-combine pattern: split rows into groups by
some column, apply an aggregation (sum, mean, count...) within each
group, then combine the results back into one object.
import pandas as pd
df = pd.DataFrame({
"dept": ["eng", "eng", "sales", "sales"],
"salary": [100, 200, 150, 250],
})
print(df.groupby("dept")["salary"].sum())
# eng 300
# sales 400
.agg([...]) computes several aggregations at once, returning a DataFrame with one column per aggregation — much more common in practice than a single .sum() or .mean() call.
Beyond .sum()/.mean(), .agg() accepts any list of aggregation
functions, or even a dict mapping different columns to different
aggregations:
df.groupby("dept").agg({
"salary": "mean",
"name": "count",
})
The result of a groupby is indexed by the group key — that's why
group_sum(...).to_dict() (in the exercise below) naturally produces
{group: value} pairs, and why sorting the result by value needs
.items() first, since the group key lives in the index, not a regular
column.
Write `group_sum(data, group_col, value_col)`: build a DataFrame from `data`, group by `group_col`, and return the sum of `value_col` per group as a dict (`.to_dict()`).
Write `group_mean_sorted(data, group_col, value_col)`: group by `group_col`, compute the mean of `value_col` per group, and return a list of `(group, mean)` tuples sorted by mean descending.
What three steps does df.groupby('dept')['salary'].sum() perform, conceptually?
You can group rows by a column and aggregate another column per group, including sorting groups by their aggregated value.