Grouping and Aggregations (groupby, agg)
The idea
Section titled “The idea”groupby answers questions like:
- Average revenue per city?
- Total orders per customer?
- Highest score per class?
Think: split → apply → combine.
Example dataset
Section titled “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
Section titled “Basic aggregations”Sum per city
Section titled “Sum per city”print(sales.groupby("city")["amount"].sum())Mean per city
Section titled “Mean per city”print(sales.groupby("city")["amount"].mean())Multiple aggregations with agg
Section titled “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
Section titled “Group by multiple keys”summary = (
sales.groupby(["city", "category"])
.agg(total_amount=("amount", "sum"), orders=("amount", "count"))
.reset_index()
)
print(summary)Common gotchas
Section titled “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
Section titled “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
Section titled “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
Section titled “🧪 Try It Yourself”Exercise 1 – Group and Sum
Section titled “Exercise 1 – Group and Sum”Exercise 2 – Multiple Aggregations With agg
Section titled “Exercise 2 – Multiple Aggregations With agg”Exercise 3 – Reset the Index After Grouping
Section titled “Exercise 3 – Reset the Index After Grouping”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.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading