Run pandas Online

pandas GroupBy with Examples

Split rows into groups, calculate an average or total for each, and combine the results into a report.

  • Intermediate
  • 2 min read
  • 1 runnable example
What you'll learn
  • groupby(column)
  • mean(), sum() and count() per group
  • agg() for several results
results.groupby("team")["score"].mean()
  1. 1A: 80, 90 | B: 70, 100Split by team
  2. 2mean()Apply to each group
  3. 3A 85.0 | B 85.0Combine

Split, apply, combine

The problem

"What is the average score per team?" "Total sales per month?" Answering these by looping over rows and keeping a dictionary of totals is error-prone. groupby does the splitting and summarizing for you.

Think of it like this

groupby is like sorting receipts into envelopes by shop, adding up each envelope and writing the totals on one summary sheet. Split into envelopes, calculate per envelope, combine the results.

From envelopes of receipts to code
groupby("team")✉️ One envelope per team
["score"]🧾 Look at the score in each receipt
.mean()🧮 Average each envelope
.reset_index()📄 Write the results on one sheet
Split, apply, combine.
In one sentence

groupby splits the rows of a DataFrame into groups by one or more columns, applies a calculation to each group and combines the results.

Key points

  1. results.groupby("team") splits the rows into team A and team B.
  2. ["score"].mean() averages the scores within each team.
  3. Both teams average 85.0 here.
  4. reset_index() turns the team labels back into a normal column.

When should you use it?

  • Summaries per category: average per class, total per month, count per country.
  • Comparing groups side by side.
  • Building reports and features for analysis.

When not to use it

  • A summary with both rows and columns as categories: a pivot table is easier to read.
  • A single overall number: call .mean() on the column directly.

Example code

Run code →
main.py
import pandas as pd

results = pd.DataFrame({
    "team": ["A", "A", "B", "B"],
    "score": [80, 90, 70, 100],
})

averages = results.groupby("team")["score"].mean().reset_index()
print(averages)
Get a Run button for this example

Result of running the code

team  score
0    A   85.0
1    B   85.0

Code explanation

Rows are grouped by team, then the score column is averaged for each group. Reset_index converts the result back to a DataFrame.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Add rows, columns, and missing values.
  2. Combine filtering, sorting, and groupby into a small report.
  3. Load a real file, inspect dtypes, and handle invalid data.
Run in the Python compiler →

Common mistakes

Forgetting to choose a column

Without a column, mean() is applied to every column, which fails or surprises with text columns.

Problem
results.groupby("team").mean()
Fix
results.groupby("team")["score"].mean()

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges