Saturday , December 5 2026
Groupby in Pandas - Data Science Tutorials

Groupby in Pandas – Data Science Tutorials

Updated: 28 November 2026Level: BeginnerReading time: about 10 minutespandas 2.x / 3.x

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

Example
print(df.groupby('city')['marks'].mean())
Output
city
Delhi       80.666667
Ludhiana    84.500000
Mohali      60.000000
Name: marks, dtype: float64

Several Statistics with agg

Example
print(df.groupby('city')['marks'].agg(['count', 'mean', 'max']).round(1))
Output
          count  mean  max
city                      
Delhi         3  80.7   95
Ludhiana      2  84.5   88
Mohali        1  60.0   60

Named Aggregation

Example
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.

Output
          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

Example
print(df.groupby(['city', 'gender'])['marks'].mean())
Output
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

Example
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.

Output
       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

Example
print(df.groupby('city').filter(lambda g: len(g) >= 2)['city'].unique().tolist())
Output
['Delhi', 'Ludhiana']

Useful Options

Example
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

  1. Find the topper in each city with idxmax.
  2. 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

About Machine Learning

Check Also

Exploratory Data Analysis (EDA) in Python: Step-by-Step Checklist

A step-by-step EDA checklist in pandas with tested outputs: shape, missing values, describe, value counts, groupby, correlations and charts.