Latticework

Command Palette

Search for a command to run...

Pandas

GroupBy

16 min

Explanation

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
Try it

.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.

Loading editor…
Explanation

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.

Exercise

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()`).

Exercise

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.

Quiz

What three steps does df.groupby('dept')['salary'].sum() perform, conceptually?

Checkpoint

You can group rows by a column and aggregate another column per group, including sorting groups by their aggregated value.