Lesson 10 · Mastering Pandas
Introduction to Data Analysis with the Titanic Dataset Using Pandas
Let us dive into a classic real-world dataset: the Titanic passenger list. You will practice loading, cleaning, exploring, and analyzing this famous data…
- CourseMastering Pandas
- Lesson10 of 44
- Video13 min
- FormatJupyter notebook · 15 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbMini Project: Titanic Dataset Analysis#
Let us dive into a classic real-world dataset: the Titanic passenger list.
You will practice loading, cleaning, exploring, and analyzing this famous data using pandas.
By the end, you will feel comfortable with core pandas tasks and ready for your own projects.
# Always suppress warnings to keep output tidy
import warnings; warnings.filterwarnings('ignore')
import numpy as np
np.random.seed(42)
# 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))
# List Titanic columns and their data types
print(df.dtypes)
Data at a Glance#
- Rows are passengers.
- Columns like 'Survived', 'Pclass', 'Sex', 'Age', and others give information about each one.
- Our goal: answer questions and find patterns.
# How many passengers survived?
survived_count = df['Survived'].value_counts()
print(survived_count)
# Calculate the survival rate
rate = df['Survived'].mean()
print(f'Survival rate: {rate:.2%}')
Cleaning: Checking for Missing Data#
Often data is not perfect. Let us spot what is missing.
# Count missing values in each column
print(df.isnull().sum())
# Fill missing ages with the median value
median_age = df['Age'].median()
df['Age'].fillna(median_age, inplace=True)
print(df['Age'].isnull().sum())
# Drop columns we do not need for a simple analysis
cols_to_drop = ['Cabin', 'Ticket', 'Name']
df.drop(columns=cols_to_drop, inplace=True)
print(df.columns)
Data Filtering: Women and Children First?#
Let us explore survival rates for females and for children under 16.
# What percent of women survived?
female_survival = df[df['Sex'] == 'female']['Survived'].mean()
print(f'Female survival rate: {female_survival:.2%}')
# What percent of children under 16 survived?
children_survival = df[df['Age'] < 16]['Survived'].mean()
print(f'Child survival rate (age < 16): {children_survival:.2%}')
# Comparing survival by passenger class
print(df.groupby('Pclass')['Survived'].mean())
Aggregation Practice#
Try GroupBy aggregations on your own:
- What is the average fare per class?
- Are males or females older on average?
Pause the video, try, and resume for answers!
# Mini visualization: survival rate by sex
import matplotlib.pyplot as plt
df.groupby('Sex')['Survived'].mean().plot(kind='bar')
plt.title('Survival Rate by Sex')
plt.ylabel('Survival Rate')
plt.show()
# Which family groupings had the most survivors?
df['FamilySize'] = df['SibSp'] + df['Parch'] + 1
print(df.groupby('FamilySize')['Survived'].sum().sort_values(ascending=False).head())
# Create a new feature: Was the fare high?
df['HighFare'] = df['Fare'] > 100
print(df['HighFare'].value_counts())
Recap: What Have You Practiced?#
- Loading, inspecting, and summarizing Titanic data
- Cleaning: handling missing data and dropping columns
- Filtering by gender, age, and class
- Grouping and aggregating for useful summaries
- Creating new features
- Mini visualizations
Next: Try the challenge below and let us know what else you want to learn!
# Challenge: Try this yourself!
avg_fare_women_firstclass = df[(df['Sex'] == 'female') & (df['Pclass'] == 1)]['Fare'].mean()
print(f'Average fare paid by women in first class: {avg_fare_women_firstclass:.2f}')
Nice Work! Practice Next Steps#
- Experiment by changing the filters, columns, or aggregation methods
- Write your own 'mini-reports' answering new questions
Keep learning, and see you in the next lesson!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



