pandas GroupBy
GroupBy follows a split-apply-combine process: split rows into groups, calculate a value, and combine the results.
What is pandas GroupBy?
GroupBy follows a split-apply-combine process: split rows into groups, calculate a value, and combine the results.
Group DataFrame rows and calculate aggregated values with pandas.
When should you use it?
- Read, clean, and transform tabular data.
- Analyze data from CSV, Excel, APIs, or databases.
- Prepare reports, statistics, and chart data.
Example 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)
Expected output
team score
0 A 85.0
1 B 85.0
How it works
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.