GroupBy answers questions like “What is the average mark per city?” It follows three steps: split the data into groups, apply a function to each group, and combine the results.
Prerequisites
Descriptive Statistics. Example data:
import pandas as pd
df = pd.DataFrame({
'city': ['Delhi', 'Ludhiana', 'Delhi', 'Mohali', 'Ludhiana', 'Delhi'],
'gender': ['M', 'F', 'F', 'M', 'M', 'F'],
'marks': [70, 88, 95, 60, 81, 77],
'fee': [5000, 4500, 5000, 4000, 4500, 5000]
})
Basic GroupBy
print(df.groupby('city')['marks'].mean())
city Delhi 80.666667 Ludhiana 84.500000 Mohali 60.000000 Name: marks, dtype: float64
Several Statistics with agg
print(df.groupby('city')['marks'].agg(['count', 'mean', 'max']).round(1))
count mean max city Delhi 3 80.7 95 Ludhiana 2 84.5 88 Mohali 1 60.0 60
Named Aggregation
summary = df.groupby('city').agg(
students=('marks', 'size'),
avg_marks=('marks', 'mean'),
total_fee=('fee', 'sum')
).round(1)
print(summary)
Explanation: Named aggregation gives clean column names in one step.
students avg_marks total_fee city Delhi 3 80.7 15000 Ludhiana 2 84.5 9000 Mohali 1 60.0 4000
Group by Several Columns
print(df.groupby(['city', 'gender'])['marks'].mean())
city gender
Delhi F 86.0
M 70.0
Ludhiana F 88.0
M 81.0
Mohali M 60.0
Name: marks, dtype: float64
transform: Keep the Original Shape
df['city_avg'] = df.groupby('city')['marks'].transform('mean').round(1)
df['above_avg'] = df['marks'] > df['city_avg']
print(df[['city', 'marks', 'city_avg', 'above_avg']])
Explanation: transform returns one value per original row, so you can compare each row with its group.
city marks city_avg above_avg 0 Delhi 70 80.7 False 1 Ludhiana 88 84.5 True 2 Delhi 95 80.7 True 3 Mohali 60 60.0 False 4 Ludhiana 81 84.5 False 5 Delhi 77 80.7 False
filter: Keep Whole Groups
print(df.groupby('city').filter(lambda g: len(g) >= 2)['city'].unique().tolist())
['Delhi', 'Ludhiana']
Useful Options
df.groupby('city', as_index=False)['marks'].mean() # city stays a column
df.groupby('city')['marks'].mean().sort_values(ascending=False)
Common Errors
| Problem | Cause and fix |
|---|---|
TypeError: agg function failed / could not convert string |
You aggregated text columns with mean. Select numeric columns first, or pass numeric_only=True. |
Practice Exercises
- Find the topper in each city with idxmax.
- Calculate each student’s share of their city’s total fee using transform.
Interview Questions
Q: agg vs transform?
agg returns one row per group; transform returns a value for every original row.
Q: What is split-apply-combine?
The pattern groupby follows: split into groups, apply a function, combine results.
Summary
Group with groupby, summarise with mean/agg/named aggregation, use transform to add group statistics to rows, and filter to keep groups.
Next: Pivot Tables · Data Visualization
Machine Learning Tutorials, Courses and Certifications