AtomLearnAtomLearn
DashboardGoalsPathAchievementsReviewSign In
pandasNot Started

groupby

Split data into groups and compute aggregations — the pandas equivalent of SQL GROUP BY

0%
Knowledge0%
Learn & Drill
Fluency0%
Drill & Speed
Retention0%
Mastery & Review
Confidence0%
All modes
Practice

Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.

Upgrade
Knowledge
Fluency
Retention

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

groupby() follows the split → apply → combine pattern: 1. Split the DataFrame into groups based on a column 2. Apply an aggregation function to each group 3. Combine results back into a DataFrame

python
# Average salary by department
df.groupby('department')['salary'].mean()

# Multiple aggregations
df.groupby('department').agg({
    'salary': ['mean', 'max', 'count'],
    'age':    'mean'
})

# Group by multiple columns
df.groupby(['department', 'city'])['salary'].mean()

Common aggregation functions:

mean(), sum(), count(), max(), min(), std(), median()

reset_index() — groupby results often have the grouping column as the index. Use reset_index() to turn it back into a regular column: ``python result = df.groupby('city')['sales'].sum().reset_index()

Examples

Sales analysis by region

agg() lets you apply different functions to different columns

import pandas as pd

df = pd.DataFrame({'region':['North','South','North','South','North'],'sales':[100,150,200,130,180],'returns':[5,10,8,12,6]})

# Total sales per region
print(df.groupby('region')['sales'].sum())
# North    480
# South    280

# Multiple stats
print(df.groupby('region').agg({'sales':'sum','returns':'mean'}))

How well did you understand this?

Next in pandas

Merge & Join DataFrames

Continue