Module 16: Capstone Project
Learning Objectives
By the end of this module, you will be able to:
Design and execute a complete data analysis project from start to finish
Collect, clean, and explore real-world datasets independently
Apply the full Pandas toolkit: groupBy, merge, time series, visualisation
Document your analysis and generate professional reports
Publish your project on GitHub for portfolio
Note
The capstone project is the culmination of this course. It is designed to simulate a real-world data analysis workflow, requiring you to integrate all the skills you have learned across Modules 1–15.
Project Overview
You will complete an end-to-end data analysis project of your choice. The project must include:
Phase |
Description |
Weight |
|---|---|---|
Data Collection |
Acquire data from public sources or generate synthetic data |
10% |
Data Cleaning |
Handle missing values, duplicates, type conversion |
15% |
Exploratory Data Analysis (EDA) |
Summary statistics, data inspection, initial insights |
20% |
Data Transformation |
GroupBy, pivot tables, merges, feature engineering |
20% |
Visualisation |
Charts, dashboards, visual storytelling |
20% |
Documentation & Delivery |
Report, code comments, GitHub publication |
15% |
Phase 1: Project Selection
Choose one of the following project themes, or propose your own:
Recommended Project Themes
Sales and Revenue Analysis — Analyser sales data, identify trends, forecast future performance
COVID-19 or Health Data Analysis — Track cases, vaccinations, and public health metrics
Climate Change Analysis — Temperature trends, precipitation patterns, extreme events
Agricultural Yield Prediction — Crop yields, weather impacts, fertiliser effectiveness
Remote Sensing Vegetation Monitoring — NDVI trends, deforestation detection, phenology
Water Resources Assessment — River flow, reservoir levels, drought analysis
Population Demographics — Age pyramids, urbanisation, migration patterns
Customer Segmentation — Behavioural analysis, churn prediction, lifetime value
Stock Market Analysis — Price trends, volatility, portfolio optimisation
Sports Analytics — Player performance, team statistics, game outcomes
Tip
Choose a topic you are genuinely interested in. You will spend significant time on this project, so passion for the subject will sustain your motivation through challenging phases.
Phase 2: Data Collection
Public Data Sources
Source |
URL |
Type |
|---|---|---|
Kaggle |
General purpose |
|
US government data |
||
World Bank |
Global development |
|
UN Data |
International statistics |
|
NASA Earth Data |
Satellite and climate |
|
USGS Earth Explorer |
Satellite imagery |
|
FAO Stat |
Agriculture data |
|
Our World in Data |
Global health/development |
Data Requirements
Your dataset should meet these minimum criteria:
Rows: At least 1,000 records (or equivalent time series length)
Columns: At least 5–10 features/variables
Complexity: Include at least one of: missing values, categorical data, date/time columns, or multiple tables that need merging
# Example: Loading data for the project
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Load your dataset
# df = pd.read_csv("your_dataset.csv")
# df = pd.read_excel("your_data.xlsx", sheet_name="Sheet1")
# Or generate synthetic data if needed
np.random.seed(42)
n = 5000
df = pd.DataFrame({
"Date": pd.date_range("2020-01-01", periods=n, freq="D"),
"Category": np.random.choice(["A", "B", "C", "D"], n),
"Value": np.round(np.random.uniform(10, 1000, n), 2),
"Quantity": np.random.randint(1, 100, n),
"Region": np.random.choice(["North", "South", "East", "West"], n),
"Flag": np.random.choice([0, 1], n, p=[0.8, 0.2]),
})
Phase 3: Data Cleaning
Build a robust cleaning pipeline.
def clean_capstone_data(df):
"""Standard data cleaning pipeline for capstone."""
df = df.copy()
# 1. Standardise column names
df.columns = (
df.columns
.str.strip()
.str.lower()
.str.replace(r"[^a-z0-9_]", "_", regex=True)
.str.replace(r"_+", "_", regex=True)
.str.strip("_")
)
# 2. Remove fully empty rows
df = df.dropna(how="all")
# 3. Remove duplicates
df = df.drop_duplicates().reset_index(drop=True)
# 4. Standardise missing value indicators
df = df.replace({"?": np.nan, "N/A": np.nan, "NULL": np.nan, "": np.nan, "unknown": np.nan})
# 5. Convert date columns safely
for col in df.select_dtypes(include=["object"]).columns:
try:
df[col] = pd.to_datetime(df[col], errors="raise")
except (ValueError, TypeError, AttributeError):
pass
# 6. Convert numeric columns safely
for col in df.select_dtypes(include=["object"]).columns:
try:
df[col] = pd.to_numeric(df[col], errors="raise")
except (ValueError, TypeError):
pass
# 7. Handle outliers using IQR
numeric_cols = df.select_dtypes(include=[np.number]).columns
for col in numeric_cols:
Q1 = df[col].quantile(0.01)
Q3 = df[col].quantile(0.99)
df[col] = df[col].clip(Q1, Q3)
return df
df_clean = clean_capstone_data(df)
Warning
Document every cleaning decision. When presenting your project, stakeholders will want to know why you handled missing values or outliers in a particular way.
Phase 4: Exploratory Data Analysis (EDA)
Systematically explore your dataset.
# 1. Initial inspection
print("Shape:", df_clean.shape)
print("\nData Types:")
print(df_clean.dtypes)
print("\nFirst 5 Rows:")
print(df_clean.head())
print("\nSummary Statistics:")
print(df_clean.describe(include="all"))
# 2. Missing value analysis
missing = df_clean.isna().sum()
missing_pct = (missing / len(df_clean)) * 100
missing_report = pd.DataFrame({
"Missing_Count": missing,
"Missing_Percent": missing_pct,
})
print("\nMissing Values:")
print(missing_report[missing_report["Missing_Count"] > 0])
# 3. Value counts for categorical columns
categorical_cols = df_clean.select_dtypes(include=["object", "category"]).columns
for col in categorical_cols:
print(f"\n{col} Value Counts:")
print(df_clean[col].value_counts())
# 4. Correlation analysis (numeric columns)
numeric_df = df_clean.select_dtypes(include=[np.number])
if len(numeric_df.columns) > 1:
print("\nCorrelation Matrix:")
print(numeric_df.corr())
Note
EDA is an iterative process. Follow unexpected findings — they often lead to the most interesting insights. Do not rush this phase.
Phase 5: Data Transformation and Analysis
Apply the advanced Pandas techniques you have learned.
# 1. Time series analysis (if applicable)
if "date" in df_clean.columns:
df_clean = df_clean.set_index("date")
monthly = df_clean.resample("M")["value"].agg(["mean", "sum", "std"])
print("Monthly Aggregations:")
print(monthly.head())
# 2. GroupBy analysis
if "region" in df_clean.columns:
region_stats = df_clean.groupby("region")["value"].agg(
mean_value=("mean"),
total_value=("sum"),
std_value=("std"),
count=("count"),
).round(2)
print("\nRegional Statistics:")
print(region_stats)
# 3. Pivot tables
if "category" in df_clean.columns and "region" in df_clean.columns:
pivot = pd.pivot_table(
df_clean,
values="value",
index="region",
columns="category",
aggfunc="sum",
fill_value=0,
margins=True,
)
print("\nPivot Table:")
print(pivot)
# 4. Rolling statistics (if time series)
if isinstance(df_clean.index, pd.DatetimeIndex):
df_clean["rolling_mean_7"] = df_clean["value"].rolling(window=7).mean()
df_clean["rolling_std_7"] = df_clean["value"].rolling(window=7).std()
# 5. Feature engineering
if "quantity" in df_clean.columns and "value" in df_clean.columns:
df_clean["unit_price"] = df_clean["value"] / df_clean["quantity"]
print("\nUnit Price Stats:")
print(df_clean["unit_price"].describe())
Phase 6: Visualisation
Create at least 5 visualisations that tell a compelling story.
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
# 1. Time series line chart
if isinstance(df_clean.index, pd.DatetimeIndex):
df_clean["value"].plot(
ax=axes[0, 0],
title="Value Over Time",
color="steelblue",
linewidth=1,
)
# 2. Distribution histogram
df_clean["value"].plot.hist(
ax=axes[0, 1],
bins=30,
title="Value Distribution",
edgecolor="black",
alpha=0.7,
)
# 3. Grouped bar chart
if "region" in df_clean.columns and "category" in df_clean.columns:
region_cat = df_clean.groupby(["region", "category"])["value"].sum().unstack()
region_cat.plot.bar(
ax=axes[0, 2],
title="Value by Region and Category",
edgecolor="black",
)
axes[0, 2].tick_params(axis="x", rotation=0)
# 4. Box plot
if "region" in df_clean.columns:
df_clean.boxplot(column="value", by="region", ax=axes[1, 0])
axes[1, 0].set_title("Value Distribution by Region")
axes[1, 0].set_suptitle("")
# 5. Correlation heatmap
numeric_df = df_clean.select_dtypes(include=[np.number])
if len(numeric_df.columns) > 1:
corr = numeric_df.corr()
im = axes[1, 1].imshow(corr, cmap="coolwarm", vmin=-1, vmax=1)
axes[1, 1].set_xticks(range(len(corr.columns)))
axes[1, 1].set_yticks(range(len(corr.columns)))
axes[1, 1].set_xticklabels(corr.columns, rotation=45, ha="right")
axes[1, 1].set_yticklabels(corr.columns)
axes[1, 1].set_title("Correlation Heatmap")
plt.colorbar(im, ax=axes[1, 1], shrink=0.8)
# 6. Pie chart for categorical composition
if "category" in df_clean.columns:
category_totals = df_clean.groupby("category")["value"].sum()
category_totals.plot.pie(
ax=axes[1, 2],
title="Value Composition",
autopct="%1.1f%%",
startangle=90,
)
axes[1, 2].set_ylabel("")
plt.tight_layout()
plt.savefig("capstone_visualizations.png", dpi=300, bbox_inches="tight")
plt.show()
Phase 7: Statistical Summaries
from scipy import stats
# Key metrics summary
summary = {
"Total Records": len(df_clean),
"Date Range": f"{df_clean.index.min()} to {df_clean.index.max()}" if isinstance(df_clean.index, pd.DatetimeIndex) else "N/A",
"Overall Mean": df_clean["value"].mean(),
"Overall Median": df_clean["value"].median(),
"Overall Std": df_clean["value"].std(),
"Min": df_clean["value"].min(),
"Max": df_clean["value"].max(),
}
for key, value in summary.items():
print(f"{key}: {value}")
# Statistical test (example: ANOVA for regional differences)
if "region" in df_clean.columns:
regions = [group["value"].values for name, group in df_clean.groupby("region")]
f_stat, p_value = stats.f_oneway(*regions)
print(f"\nANOVA — Regional differences in Value:")
print(f"F-statistic: {f_stat:.4f}")
print(f"P-value: {p_value:.4f}")
print(f"Significant difference: {'Yes' if p_value < 0.05 else 'No'}")
Phase 8: Documentation
Jupyter Notebook Structure
Your final notebook should follow this structure:
1. Title and Introduction
- Project title, author, date
- Problem statement and objectives
- Dataset description and source
2. Data Loading
- Import libraries
- Load dataset(s)
- Initial inspection
3. Data Cleaning
- Handle missing values
- Remove duplicates
- Convert data types
- Outlier treatment
4. Exploratory Data Analysis
- Summary statistics
- Univariate analysis
- Bivariate analysis
- Correlation analysis
5. Data Transformation
- Feature engineering
- Aggregation and grouping
- Pivot tables
- Time series resampling (if applicable)
6. Visualizations
- At least 5 meaningful charts
- Each chart with a title and interpretation
7. Key Findings
- 3–5 major insights from the analysis
- Supporting statistics and visualizations
8. Conclusion
- Summary of findings
- Limitations of the analysis
- Suggestions for future work
README.md
Create a professional README for your GitHub repository:
# Project Title
## Overview
Brief description of the project (2–3 sentences).
## Dataset
- Source: [Link to data source]
- Size: X rows × Y columns
- Time period: Start date – End date
## Tools Used
- Python 3.x
- Pandas
- Matplotlib / Seaborn
- Jupyter Notebook
## Key Findings
1. Finding 1 with supporting evidence
2. Finding 2 with supporting evidence
3. Finding 3 with supporting evidence
## Files
- `notebooks/analysis.ipynb` — Main analysis notebook
- `data/raw/` — Raw data files
- `data/processed/` — Cleaned data
- `reports/figures/` — Generated visualizations
- `reports/final_report.md` — Written report
## How to Run
1. Clone this repository
2. Install dependencies: `pip install -r requirements.txt`
3. Run the notebook: `jupyter notebook notebooks/analysis.ipynb`
## License
[Choose a license]
Phase 9: GitHub Publication
Step 1: Create a Repository
# Initialize a local repository
git init
git add .
git commit -m "Initial commit: capstone project"
# Create a repository on GitHub (via web UI or gh CLI)
# gh repo create my-capstone-project --public --source=. --remote=origin --push
Step 2: Repository Structure
my-capstone-project/
├── README.md
├── LICENSE
├── requirements.txt
├── data/
│ ├── raw/ # Original, unmodified data
│ └── processed/ # Cleaned and transformed data
├── notebooks/
│ └── analysis.ipynb # Main analysis notebook
├── reports/
│ ├── figures/ # Generated visualizations
│ └── final_report.md # Written report
├── scripts/
│ ├── data_cleaning.py
│ ├── analysis.py
│ └── visualization.py
└── .gitignore
Step 3: Best Practices
# requirements.txt content
"""
pandas>=2.0
numpy>=1.24
matplotlib>=3.7
seaborn>=0.12
scipy>=1.10
jupyter>=1.0
openpyxl>=3.1
"""
Tip
Use a .gitignore file to exclude large data files and notebook checkpoints. Add *.csv, *.xlsx, data/raw/, and .ipynb_checkpoints/ to avoid pushing large or unnecessary files.
Rubric
Criteria |
Excellent (90–100%) |
Good (75–89%) |
Satisfactory (60–74%) |
|---|---|---|---|
Data Cleaning |
All issues handled, documented decisions, reusable pipeline |
Major issues handled, some documentation |
Basic cleaning, missing documentation |
EDA |
Thorough analysis, multiple perspectives, insightful |
Good coverage, basic insights |
Minimal exploration |
Transformation |
Advanced techniques (pivot, groupBy, time series, feature engineering) |
Multiple transformation methods |
Basic operations only |
Visualisation |
5+ meaningful, well-labelled charts telling a story |
3–4 clear charts |
1–2 basic charts |
Code Quality |
Well-organised, commented, modular |
Readable, some comments |
Working but messy |
Documentation |
Professional README, clear notebook, GitHub published |
Good README and notebook |
Basic documentation |
Insights |
3–5 significant, data-backed findings |
2–3 findings with support |
1 finding or unclear |
Final Checklist
Before submitting your capstone project, verify the following:
Dataset has ≥ 1,000 records with ≥ 5 columns
Data cleaning pipeline is complete and documented
EDA includes summary statistics and data quality assessment
At least 3 different Pandas operations (groupBy, merge, pivot, resample, etc.)
At least 5 visualisations with titles and axis labels
Key findings are clearly stated with supporting evidence
Code is well-commented and follows PEP 8
README.md is complete and professional
Project is published on GitHub
All files are organised in a logical directory structure
Summary
The capstone project integrates all skills from Modules 1–15 into a complete workflow
Follow the 9-phase structure: select → collect → clean → explore → transform → visualise → summarise → document → publish
Aim for a professional, well-documented project that showcases your Pandas proficiency
GitHub publication provides a portfolio-worthy artifact for employers and collaborators
Use the rubric to self-assess before final submission