~/learn/Pandas · GroupBy & aggregation
GroupBy and aggregation
Split, apply, combine.
why this matters
"Revenue by category" or "average rating per country" — groupby answers these in one line.
Mental model
split -> apply -> combine
6 order rows -> Hardware / Audio / Furniture buckets -> one row per bucket.
groupby(...).sum() shrinks the frame; groupby(...).transform("sum") keeps all 6 rows.groupby splits rows into buckets by one or more keys, applies a function to each bucket and combines the results back into a frame.
agg computes several statistics at once and names the output columns; as_index=False keeps the key as a normal column.
transform returns a value per original row instead of per group — perfect for group shares or group-mean centring.
Common gotcha
By default groupby turns the key into the index, so summary["category"] then fails with a KeyError. Pass as_index=False, or call .reset_index(), when you want it as a normal column.
key takeaways
- groupby splits rows into groups.
- agg applies summaries per group.
- reset_index turns groups back into columns.
check your understanding
Which gives total revenue per category?
free practice
Build confidence with a question you can solve without Pro.