The idea
groupby answers questions like:
- Average revenue per city?
- Total orders per customer?
- Highest score per class?
Think: split → apply → combine.
Example dataset
import pandas as pd
sales = pd.DataFrame({
"city": ["pune", "pune", "delhi", "delhi", "delhi"],
"category": ["A", "B", "A", "A", "B"],
"amount": [100, 200, 150, 120, 300],
})
print(sales)Basic aggregations
Sum per city
print(sales.groupby("city")["amount"].sum())Mean per city
print(sales.groupby("city")["amount"].mean())Multiple aggregations with agg
summary = (
sales.groupby("city")
.agg(
total_amount=("amount", "sum"),
avg_amount=("amount", "mean"),
orders=("amount", "count"),
)
)
print(summary)Group by multiple keys
summary = (
sales.groupby(["city", "category"])
.agg(total_amount=("amount", "sum"), orders=("amount", "count"))
.reset_index()
)
print(summary)Common gotchas
- After
groupby, the grouped columns become the index. Use.reset_index()if you want them as normal columns. - Aggregation functions ignore missing numeric values by default (
NaN) in many cases.
Mental model
When you write:
sales.groupby("city")["amount"].sum()You are saying:
- Split the rows by
city - Select the
amountcolumn - Sum within each group
This pattern comes up constantly in analytics.
Visualize it
flowchart LR A["Original rows"] --> B["Split by key (city)"] B --> C1["Group: pune"] B --> C2["Group: delhi"] C1 --> D1["Apply sum()"] C2 --> D2["Apply sum()"] D1 --> E["Combine into result"] D2 --> E
🧪 Try It Yourself
Exercise 1 – Group and Sum
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 – Multiple Aggregations With agg
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 – Reset the Index After Grouping
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Check your understanding
In sales.groupby("city")["amount"].sum(), what does groupby do?
The mental model is split, apply, combine: split by city, select amount, sum within each group.
Show answer
B — Splits the rows by city so each group can be summed — The mental model is split, apply, combine: split by city, select amount, sum within each group.
With amounts pune = 100 and 200, and delhi = 150, 120 and 300, what is the sum for delhi?
150 + 120 + 300 = 570. The mean for delhi would be 190.
Show answer
C — 570 — 150 + 120 + 300 = 570. The mean for delhi would be 190.
After a groupby, where do the grouping columns end up and how do you turn them back into normal columns?
Grouped keys become the index of the result, and .reset_index() moves them back into regular columns.
Show answer
A — They become the index, and reset_index() restores them — Grouped keys become the index of the result, and .reset_index() moves them back into regular columns.
Which aggregation counts the number of orders per city?
count tallies the non-missing rows in each group. For delhi that is 3 orders.
Show answer
A — orders=("amount", "count") — count tallies the non-missing rows in each group. For delhi that is 3 orders.
Next
groupby and agg cover the essentials — continue to Advanced GroupBy (transform,
filter, named agg) for broadcasting group stats back, filtering whole groups, and
bucket analysis.