The one-line mental model
A foundation capstone proves you can take a question from raw source to written recommendation using modular, testable code â the pipeline structure matters as much as any single chart, because that is what scales to a team.
You will be able to:
- Split an analysis into collection, cleaning, analysis, and reporting modules
- Implement a cleaning stage that logs every transformation it applies
- Generate descriptive statistics, correlations, and outlier flags programmatically
- Assemble a reproducible entry point someone else can run without your notebook
Prerequisites
- !Pandas DataFrames and dtypes
- !EDA on a single dataset
- !Python modules and classes
What You'll Learn
- 1Design a directory layout for a multi-stage analysis project
- 2Write a DataCollector that loads from SQL, API, or CSV behind one interface
- 3Build a cleaning pipeline with a transformation log and quality metrics
- 4Produce an automated summary report from analysis results
Why structure beats a single mega-notebook
One notebook that loads, cleans, charts, and models feels faster on day one and becomes unmaintainable by week three. Cells get re-run out of order, hidden state hides bugs, and nobody can consume your work without opening Jupyter. The fix is not enterprise architecture â it is four small modules with clear inputs and outputs, plus a thin runner script that wires them together.
The contract between stages should be plain: each stage accepts a DataFrame (or a path), returns a DataFrame, and records what it did. That contract makes each stage unit-testable with a five-row fixture and lets you swap a CSV loader for a warehouse query without touching the analysis code.
| Stage | Input | Output | Side effect |
|---|---|---|---|
| Collect | Query, URL, or file path | Raw DataFrame | Provenance record |
| Clean | Raw DataFrame | Clean DataFrame | Cleaning log, quality metrics |
| Analyze | Clean DataFrame | Results dict | Figures on disk |
| Report | Results dict | Markdown or HTML | Final narrative file |
Collection behind one interface
Analysts pull data from three places more than anything else: a database, a REST API, and a CSV dropped by a colleague. Wrapping all three behind one small class keeps the rest of the pipeline ignorant of provenance details and makes it trivial to add a fourth source later.
# src/collect.py
import os
import requests
import pandas as pd
from sqlalchemy import create_engine
class DataCollector:
def __init__(self, sql_url: str | None = None):
self.engine = create_engine(sql_url) if sql_url else None
self.provenance = []
def from_sql(self, query: str) -> pd.DataFrame:
if self.engine is None:
raise RuntimeError("No SQL engine configured")
df = pd.read_sql(query, self.engine)
self.provenance.append({"source": "sql", "detail": query[:120],
"rows": len(df)})
return df
def from_api(self, url: str, params: dict | None = None) -> pd.DataFrame:
headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
resp = requests.get(url, headers=headers, params=params or {}, timeout=20)
resp.raise_for_status()
df = pd.DataFrame(resp.json()["results"])
self.provenance.append({"source": "api", "detail": url,
"rows": len(df)})
return df
def from_csv(self, path: str, **read_kwargs) -> pd.DataFrame:
df = pd.read_csv(path, **read_kwargs)
self.provenance.append({"source": "csv", "detail": path,
"rows": len(df)})
return df
def merge(self, left: pd.DataFrame, right: pd.DataFrame,
on: str, how: str = "inner") -> pd.DataFrame:
before = len(left)
out = left.merge(right, on=on, how=how, validate="many_to_one")
self.provenance.append({
"source": "merge", "detail": f"{how} on {on}",
"rows": len(out), "rows_before": before,
})
return out
The validate="many_to_one" argument on merge is cheap insurance: it raises immediately if the right table unexpectedly contains duplicate keys, which would otherwise multiply your grain and corrupt every downstream total.
Cleaning as a logged pipeline
The cleaning module should be the most boring code in the project â explicit, sequential, and chatty about what it changed. A fluent interface (each method returns self) keeps the runner readable while every step appends to a shared log.
# src/clean.py
import numpy as np
import pandas as pd
class DataCleaner:
def __init__(self, df: pd.DataFrame):
self.df = df.copy()
self.log = []
self._nulls_before = int(df.isna().sum().sum())
def _record(self, action: str, detail: str):
self.log.append({"action": action, "detail": detail,
"timestamp": pd.Timestamp.utcnow()})
def drop_duplicates(self, subset=None):
n = len(self.df)
self.df = self.df.drop_duplicates(subset=subset)
self._record("drop_duplicates", f"{n - len(self.df)} rows removed")
return self
def coerce_types(self, spec: dict):
for col, kind in spec.items():
if kind == "datetime":
self.df[col] = pd.to_datetime(self.df[col], errors="coerce")
elif kind == "numeric":
self.df[col] = pd.to_numeric(self.df[col], errors="coerce")
elif kind == "category":
self.df[col] = self.df[col].astype("category")
self._record("coerce_types", str(list(spec)))
return self
def impute(self, numeric_strategy="median", categorical_value="Unknown"):
num = self.df.select_dtypes(include=[np.number]).columns
cat = self.df.select_dtypes(include=["object", "category"]).columns
if numeric_strategy == "median":
self.df[num] = self.df[num].fillna(self.df[num].median())
for col in cat:
self.df[col] = self.df[col].fillna(categorical_value)
self._record("impute", f"numeric={numeric_strategy}, cat={categorical_value}")
return self
def quality_metrics(self) -> dict:
return {
"rows": len(self.df),
"cols": self.df.shape[1],
"nulls_before": self._nulls_before,
"nulls_after": int(self.df.isna().sum().sum()),
"completeness": 1 - self.df.isna().sum().sum() / self.df.size,
}
def finish(self) -> pd.DataFrame:
return self.df
After the cleaner runs, print or persist the log and the quality metrics together. Stakeholders trust numbers far more when they can see that completeness improved from 82% to 99.4% through named, reviewable steps.
Analysis and automated reporting
The analysis module turns the clean frame into a results dictionary â descriptive stats, top correlations, outlier counts â and a figure set. The report module then renders that dictionary into a markdown file. Separating them means you can regenerate the narrative from cached results without re-running heavy computation.
# src/analyze.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
class DataAnalyzer:
def __init__(self, df: pd.DataFrame):
self.df = df
self.results: dict = {}
def descriptive(self):
self.results["numeric_summary"] = self.df.describe().round(3)
self.results["categorical_summary"] = (
self.df.describe(include=["object", "category"]).round(3)
)
return self
def correlations(self, method="spearman"):
num = self.df.select_dtypes(include=[np.number])
self.results["correlation"] = num.corr(method=method).round(3)
return self
def outliers_iqr(self):
flagged = {}
for col in self.df.select_dtypes(include=[np.number]).columns:
q1, q3 = self.df[col].quantile([0.25, 0.75])
iqr = q3 - q1
lo, hi = q1 - 1.5 * iqr, q3 + 1.5 * iqr
n = int(((self.df[col] < lo) | (self.df[col] > hi)).sum())
flagged[col] = {"count": n, "pct": round(100 * n / len(self.df), 2)}
self.results["outliers"] = flagged
return self
def save_figures(self, path="reports/figures"):
import os
os.makedirs(path, exist_ok=True)
corr = self.results.get("correlation")
if corr is not None:
plt.figure(figsize=(9, 7))
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", center=0)
plt.title("Feature correlations")
plt.tight_layout()
plt.savefig(f"{path}/correlation.png", dpi=120)
plt.close()
return self
def render_report(results: dict, provenance: list, out_path: str):
lines = ["# Capstone Analysis Report", ""]
lines.append("## Provenance")
for p in provenance:
lines.append(f"- {p['source']}: {p['detail']} ({p['rows']} rows)")
lines.append("")
if "correlation" in results:
top = (results["correlation"].where(~np.eye(len(results["correlation"]), dtype=bool))
.stack().sort_values(ascending=False).head(5))
lines.append("## Top correlations")
for (a, b), v in top.items():
lines.append(f"- {a} vs {b}: {v:+.3f}")
lines.append("")
if "outliers" in results:
lines.append("## Outlier share by column")
for col, info in results["outliers"].items():
lines.append(f"- {col}: {info['count']} ({info['pct']}%)")
with open(out_path, "w", encoding="utf-8") as fh:
fh.write("\n".join(lines))
Wiring the runner
The runner is the only file a colleague needs to know. It loads data, cleans, analyzes, and writes the report â and because each stage is a class with a narrow interface, swapping in a new dataset is a configuration change, not a rewrite.
# main.py
from src.collect import DataCollector
from src.clean import DataCleaner
from src.analyze import DataAnalyzer, render_report
collector = DataCollector()
raw = collector.from_csv("data/transactions.csv")
reference = collector.from_csv("data/customers.csv")
joined = collector.merge(raw, reference, on="customer_id", how="left")
cleaned = (
DataCleaner(joined)
.drop_duplicates()
.coerce_types({"sale_date": "datetime", "amount": "numeric",
"segment": "category"})
.impute()
.finish()
)
analyzer = DataAnalyzer(cleaned)
results = (analyzer.descriptive().correlations().outliers_iqr()
.save_figures().results)
render_report(results, collector.provenance, "reports/capstone_report.md")
print("Report written to reports/capstone_report.md")
Add a handful of pytest cases around the cleaner â duplicate removal counts, type coercion, imputation null counts â and you have a project that reads like software rather than a homework dump. That difference is exactly what hiring managers look for when they open a portfolio repository.
Designing the data collection layer
The collector sits between messy reality and your analysis code. A good collector does three things: it reads from a single source of truth, it stamps every record with provenance (file path, load timestamp, row count), and it fails loudly when the source does not match the expected schema. Treat this layer like an API contract â the rest of the project depends on its stability, so changes here should be deliberate and versioned.
In practice the collector wraps pandas.read_csv or a warehouse query behind a small class that records what it loaded. That record becomes the cleaning log's first entry and gives future reviewers a way to verify that today's analysis used the same inputs as yesterday's. When the source grows or renames columns, the collector is the single place that needs updating; nothing downstream should hard-code column names or file paths.
Keep the collector free of transformation logic. Casting a timestamp or renaming a column for readability is fine, but joins, filters, and imputation belong in the cleaning stage where they are logged and reviewable. Mixing collection and cleaning makes it impossible to answer the simplest reproducibility question: did the data change, or did the code change?
From cleaning log to analysis decisions
The cleaning log is not just an audit trail â it is the bridge between raw data and the analytical choices that follow. Every decision recorded there (drop a row, fill a median, clip an outlier) narrows or widens the population your conclusions apply to. Before modeling, read the log end to end and ask whether each choice still holds given the question you are answering. A log entry that made sense for a revenue analysis may silently bias a churn analysis if the dropped rows are concentrated in one customer segment.
This is also where most capstone projects lose points on rigor. Reviewers do not expect perfect data; they expect you to have thought about what imperfection costs. A short paragraph per decision â what was done, why, and what the residual risk is â elevates the project from a homework exercise to something a stakeholder could actually trust.