pandas GroupBy with Examples
Split rows into groups, calculate an average or total for each, and combine the results into a report.
- groupby(column)
- mean(), sum() and count() per group
- agg() for several results
- 1
A: 80, 90 | B: 70, 100Split by team - 2
mean()Apply to each group - 3
A 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.
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 sheetgroupby 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
results.groupby("team")splits the rows into team A and team B.["score"].mean()averages the scores within each team.- Both teams average 85.0 here.
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
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)
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.
- Add rows, columns, and missing values.
- Combine filtering, sorting, and groupby into a small report.
- Load a real file, inspect dtypes, and handle invalid data.
Common mistakes
Forgetting to choose a column
Without a column, mean() is applied to every column, which fails or surprises with text columns.
results.groupby("team").mean()
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.
- Tournament Standings Rank teams from match records. Medium
- Naive Bayes Classifier Predict a class from categorical features with Bayes' theorem and Laplace smoothing. Medium