groupby: Totals by Group
groupby is the heart of analysis: split the rows into groups, calculate something for each group, and combine the answers. It's like a pivot table in Excel.
Business questions are usually "per" something: revenue per city, orders per month, average order per customer. groupby splits the data into groups, calculates for each, and combines the results - the pandas version of a pivot table or SQL GROUP BY.
Example
Several results at once: agg
Example
Grouping by two columns
Example
Counting and top items
Example
Add
.reset_index() after a groupby to turn the group labels back into normal columns - handy before saving or charting.Key points
- groupby(col)[value].sum() totals per group.
- agg computes several results at once.
- reset_index turns group labels back into columns.
📝 Test yourself
1. What does df.groupby("city")["amount"].sum() give?
2. Which method calculates several results per group?
3. Fill in the method that counts how often each value appears:
df["product"].()
