Skip to content

Grouping and Aggregations (groupby, agg)

groupby answers questions like:

  • Average revenue per city?
  • Total orders per customer?
  • Highest score per class?

Think: split → apply → combine.

Sales sample
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)
Sum per city
print(sales.groupby("city")["amount"].sum())
Mean per city
print(sales.groupby("city")["amount"].mean())
Multiple metrics
summary = (
    sales.groupby("city")
    .agg(
        total_amount=("amount", "sum"),
        avg_amount=("amount", "mean"),
        orders=("amount", "count"),
    )
)
 
print(summary)
Group by city and category
summary = (
    sales.groupby(["city", "category"])
    .agg(total_amount=("amount", "sum"), orders=("amount", "count"))
    .reset_index()
)
 
print(summary)
  • 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.

When you write:

python
sales.groupby("city")["amount"].sum()

You are saying:

  • Split the rows by city
  • Select the amount column
  • Sum within each group

This pattern comes up constantly in analytics.

diagram Split, apply, combine mermaid
groupby splits rows into groups, applies a function to each group independently, then combines the results into one table.
sketch Split → apply → combine p5.js
groupby splits rows by key, applies an aggregation to each group separately, then combines the answers into one table.

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.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading