The split-apply-combine model
What it is
groupby(key) splits rows into groups, applies a function to each, and combines the results. The key becomes the index unless you pass as_index=False.
Why it matters
It is the workhorse of feature engineering: per-user counts, per-store averages, per-session durations are all one group-by.
In the real world: Total revenue per region: split orders by region, add up each group, and put the results side by side.
Visual example
GroupBygroupby splits rows by key, applies a function to each group, then combines one answer per group.
Apply: sum each group
a: 10 + 5 = 15
b: 7 = 7
Why this matters
Per-user counts, per-store averages, per-session durations — most feature engineering is one group-by.
Common misconception
Wrong idea: groupby gives back the grouped rows.
Correct idea: it gives one row per group, with the key as the index — pass as_index=False to keep it as a column.
- 1SplitRows are sorted into one group per key.
- 2ApplyThe function runs on each group separately.
- 3CombineThe answers are stacked, keyed by group.
df.groupby("customer_id")["total"].sum()
df.groupby(["country", "tier"])["total"].mean()
df.groupby("customer_id", as_index=False)["total"].sum() # key stays a column