← Learning Hub
Intermediate

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
You can edit this code.

Several results at once: agg

Example
You can edit this code.

Grouping by two columns

Example
You can edit this code.

Counting and top items

Example
You can edit this code.
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"].()