Mathew K Analytics

Lesson 29 · Mastering Pandas

Master Grouping and Aggregation in Python for Effective Data Analysis

Grouping and aggregation let you answer powerful business questions. You will learn to use groupby(), calculate summaries, and uncover trends. We will…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Lesson Overview: Grouping Data and Aggregation with pandas#

Grouping and aggregation let you answer powerful business questions. You will learn to use groupby(), calculate summaries, and uncover trends.

We will practice with the Titanic dataset, a classic for passenger analytics!

import warnings
import numpy as np
np.random.seed(42)
warnings.filterwarnings("ignore")
# Data setup (Titanic Dataset)
import pandas as pd
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
(891, 12)
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  

Exploring the Titanic Data#

Before we dive into grouping, notice columns like 'Pclass', 'Sex', and 'Survived'. These will help us segment the data in meaningful ways.

# Check for missing values
df.isnull().sum()
PassengerId      0
Survived         0
Pclass           0
Name             0
Sex              0
Age            177
SibSp            0
Parch            0
Ticket           0
Fare             0
Cabin          687
Embarked         2
dtype: int64
# Fill missing 'Age' values with the median
df['Age'].fillna(df['Age'].median(), inplace=True)
# See unique passenger classes
print(df['Pclass'].unique())
[3 1 2]

What is groupby in pandas?#

groupby() lets you split your data into groups based on the values in one or more columns. For example, you can ask: what is the average age of survivors in each class?

# Group by 'Pclass' and get mean age
pclass_age = df.groupby('Pclass')['Age'].mean()
print(pclass_age)
Pclass
1    36.812130
2    29.765380
3    25.932627
Name: Age, dtype: float64
# Group by 'Sex' and see survival rate
survival_rate = df.groupby('Sex')['Survived'].mean()
print(survival_rate)
Sex
female    0.742038
male      0.188908
Name: Survived, dtype: float64
# Group by multiple columns: class and sex
survival_by_group = df.groupby(['Pclass', 'Sex'])['Survived'].mean()
print(survival_by_group)
Pclass  Sex   
1       female    0.968085
        male      0.368852
2       female    0.921053
        male      0.157407
3       female    0.500000
        male      0.135447
Name: Survived, dtype: float64
# Find mean, median, and max fare by class
fare_stats = df.groupby('Pclass')['Fare'].agg(['mean', 'median', 'max'])
print(fare_stats)
             mean   median       max
Pclass                              
1       84.154687  60.2875  512.3292
2       20.662183  14.2500   73.5000
3       13.675550   8.0500   69.5500

Quick practice: Group and summarize#

Try grouping by 'Embarked' and counting how many passengers from each port survived.

# Group by 'Embarked' and 'Pclass', counting survivors per group
survivor_counts = df.groupby(['Embarked', 'Pclass'])['Survived'].sum().unstack()
print(survivor_counts)
Pclass     1   2   3
Embarked            
C         59   9  25
Q          1   2  27
S         74  76  67
# Group by 'Sex' and describe ages
age_stats = df.groupby('Sex')['Age'].describe()
print(age_stats)
        count       mean        std   min   25%   50%   75%   max
Sex                                                              
female  314.0  27.929936  12.860189  0.75  21.0  28.0  35.0  63.0
male    577.0  30.140676  13.050847  0.42  23.0  28.0  35.0  80.0
# Custom aggregation: average fare per survival status and class
def mean_fare(x):
    return round(x.mean(), 2)

fare_grouped = df.groupby(['Survived', 'Pclass'])['Fare'].agg(mean_fare)
print(fare_grouped)
Survived  Pclass
0         1         64.68
          2         19.41
          3         13.67
1         1         95.61
          2         22.06
          3         13.69
Name: Fare, dtype: float64
# Filter: Only show groups with more than 100 passengers
sizes = df.groupby('Pclass').filter(lambda x: len(x) > 100)
print(sizes['Pclass'].value_counts())
Pclass
3    491
1    216
2    184
Name: count, dtype: int64
# Pivot table recreation: survival rate by class and gender
pivot = df.pivot_table(values='Survived', index='Pclass', columns='Sex', aggfunc='mean')
print(pivot)
Sex       female      male
Pclass                    
1       0.968085  0.368852
2       0.921053  0.157407
3       0.500000  0.135447
# Visualize groupby: average age by class
import matplotlib.pyplot as plt
grouped_avg_age = df.groupby('Pclass')['Age'].mean()
grouped_avg_age.plot(kind='bar', color='skyblue')
plt.ylabel('Average Age')
plt.title('Average Age by Passenger Class')
plt.show()
No description has been provided for this image

Challenge: Find the youngest and oldest survivor in each class#

Use groupby and aggregation to figure this out!

# Youngest and oldest survivor per class
survivors = df[df['Survived'] == 1]
result = survivors.groupby('Pclass')['Age'].agg(['min', 'max'])
print(result)
         min   max
Pclass            
1       0.92  80.0
2       0.67  62.0
3       0.42  63.0

Recap: Groupby and Aggregations in pandas#

  • groupby lets you split, summarize, and re-combine data.
  • Aggregations provide flexible summaries like mean, min, max, and more.
  • Try groupby with your own datasets and real-world questions!

Want more data science tutorials?#

Subscribe to our channel for more pandas videos and request topics in the comments. Your feedback shapes our next deep dive!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.