Python Central HubSign in

Data Analytics with Python / Phase 3: Data Manipulation with Pandas

Grouping and Aggregations (groupby, agg)

Use groupby to summarize data and compute metrics like count, mean, sum, and multiple aggregations.

The idea

groupby answers questions like:

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

Think: split → apply → combine.

Example dataset

Python
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

Python
print(sales.groupby("city")["amount"].sum())

Mean per city

Python
print(sales.groupby("city")["amount"].mean())

Multiple aggregations with agg

Python
summary = (
    sales.groupby("city")
    .agg(
        total_amount=("amount", "sum"),
        avg_amount=("amount", "mean"),
        orders=("amount", "count"),
    )
)
 
print(summary)

Group by multiple keys

Python
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:

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.

Visualize it

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.

🧪 Try It Yourself

Exercise 1 – Group and Sum

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Multiple Aggregations With agg

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Reset the Index After Grouping

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Check your understanding

quizCheck yourself
  1. In sales.groupby("city")["amount"].sum(), what does groupby do?

    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.

  2. With amounts pune = 100 and 200, and delhi = 150, 120 and 300, what is the sum for delhi?

    Show answer

    C — 570 — 150 + 120 + 300 = 570. The mean for delhi would be 190.

  3. After a groupby, where do the grouping columns end up and how do you turn them back into normal 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.

  4. Which aggregation counts the number of orders per city?

    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.

Was this page helpful?

Let us know how we did