Python Master Course V2 — 130. Data Foundations Capstone: An Auditable Analysis
What you will be able to do
- Combine cleaning, EDA and statistical estimation
- State assumptions, limitations and reproducible data lineage
- Package an analysis with checks and a concise evidence-based report
Prerequisites: 121–129: numerical, tabular and statistical foundations; 120: reproducible project practice.
Your local workspace
Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson130, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.
Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.
python -m pip install numpy pandas matplotlib pytestThe examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.
Capstone brief: an analysis that another person can audit
Produce a local analysis bundle for synthetic service deliveries. The bundle must contain generation code, immutable raw input for that run, cleaned records, a quality audit, three plots, a bootstrap interval and a concise non-causal report. The purpose is to connect numerical operations with data provenance and honest interpretation, not to create the most impressive-looking chart.
The schema is explicit: delivery_id identifies a delivery, route is A or B, distance_km is a positive measurement and minutes is a positive duration. One row represents one delivery. The generator creates 30 valid rows, then deliberately adds one exact duplicate and one invalid negative-duration row. All values are artificial and require no external data rights or private records.
The analysis asks whether average duration differs between the two observed route groups. Define the effect as B minus A in minutes. The bootstrap treats each route's rows as independent, exchangeable draws from its target route population. This assumption fits the simplified independent synthetic generator more closely than many real operational datasets; repeated drivers, shared weather or temporal trends would require a different uncertainty design.
Preserve the raw table before cleaning and retain source-row identifiers. Exclude exact duplicates according to the declared rule, quarantine invalid values and reconcile every row. Plot the distribution, distance relationship and route means. Report sample sizes and a percentile bootstrap interval, while stating that a descriptive comparison in generated data establishes no real-world causal route effect.
A complete local analysis pipeline
Save analysis.py. The program creates analysis-output only if it does not already exist, protecting earlier evidence. Archive or rename a previous output directory deliberately before rerunning. Separate seeds control data generation and bootstrap resampling so changing the number of bootstrap draws does not silently change the dataset.
from pathlib import Path
import hashlib
import json
import platform
import importlib.metadata
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def generate_data():
rng = np.random.default_rng(42)
route = np.where(np.arange(30) % 2 == 0, "A", "B")
distance = rng.integers(1, 6, size=30)
minutes = 8 + 3 * distance + 2 * (route == "B") + rng.uniform(-1, 1, 30)
base = pd.DataFrame({
"delivery_id": np.arange(1, 31), "route": route,
"distance_km": distance, "minutes": np.round(minutes, 2),
})
invalid = pd.DataFrame({"delivery_id": [31], "route": ["A"],
"distance_km": [2], "minutes": [-5.0]})
return pd.concat([base, base.iloc[[0]], invalid], ignore_index=True)
def clean_data(raw):
work = raw.copy()
work.insert(0, "source_row", np.arange(len(work)))
duplicate = work.duplicated(list(raw.columns), keep="first")
valid = (work["route"].isin(["A", "B"]) &
np.isfinite(work["distance_km"]) & work["distance_km"].gt(0) &
np.isfinite(work["minutes"]) & work["minutes"].gt(0) &
work["delivery_id"].notna())
clean = work.loc[~duplicate & valid].copy()
if not clean["delivery_id"].is_unique:
raise ValueError("conflicting delivery IDs require review")
rejected = work.loc[duplicate | ~valid].copy()
rejected["reason"] = np.where(duplicate.loc[rejected.index],
"exact duplicate", "invalid value")
audit = {"raw": len(raw), "duplicates": int(duplicate.sum()),
"invalid_nonduplicates": int((~valid & ~duplicate).sum()),
"clean": len(clean)}
if audit["raw"] != audit["duplicates"] + audit["invalid_nonduplicates"] + audit["clean"]:
raise ValueError("audit does not reconcile")
return clean, rejected, audit
def estimate_difference(clean):
a = clean.loc[clean["route"].eq("A"), "minutes"].to_numpy()
b = clean.loc[clean["route"].eq("B"), "minutes"].to_numpy()
if min(len(a), len(b)) < 2:
raise ValueError("need at least two observations per route")
rng = np.random.default_rng(123)
samples_a = rng.choice(a, size=(5000, len(a)), replace=True).mean(axis=1)
samples_b = rng.choice(b, size=(5000, len(b)), replace=True).mean(axis=1)
interval = np.quantile(samples_b - samples_a, [0.025, 0.975])
return float(b.mean() - a.mean()), interval
def make_plots(clean, output):
fig, axes = plt.subplots(1, 3, figsize=(14, 4), constrained_layout=True)
axes[0].hist(clean["minutes"], bins=8, edgecolor="white", color="#2563eb")
axes[0].set(xlabel="Duration (minutes)", ylabel="Deliveries", title="Distribution")
for route, marker, color in [("A", "o", "#2563eb"), ("B", "s", "#c2410c")]:
rows = clean.loc[clean["route"].eq(route)]
axes[1].scatter(rows["distance_km"], rows["minutes"],
label=route, marker=marker, color=color)
axes[1].set(xlabel="Distance (km)", ylabel="Duration (minutes)",
title="Distance relationship")
axes[1].legend(title="Route")
means = clean.groupby("route", sort=True)["minutes"].mean()
axes[2].bar(means.index, means.values, color=["#2563eb", "#c2410c"])
axes[2].set(xlabel="Route", ylabel="Mean minutes", title="Route means (n=15 each)")
axes[2].set_ylim(bottom=0)
fig.suptitle("Synthetic deliveries: descriptive analysis")
fig.savefig(output / "eda.png", dpi=150)
plt.close(fig)
def main():
output = Path("analysis-output")
output.mkdir(exist_ok=False)
raw = generate_data()
raw_path = output / "raw.csv"
raw.to_csv(raw_path, index=False)
clean, rejected, audit = clean_data(raw)
clean.to_csv(output / "clean.csv", index=False)
rejected.to_csv(output / "quarantine.csv", index=False)
(output / "audit.json").write_text(json.dumps(audit, indent=2), encoding="utf-8")
effect, interval = estimate_difference(clean)
make_plots(clean, output)
summary = {
"effect_B_minus_A_minutes": effect,
"bootstrap_percentile_95_interval": interval.tolist(),
"resamples": 5000, "data_seed": 42, "bootstrap_seed": 123,
"raw_sha256": hashlib.sha256(raw_path.read_bytes()).hexdigest(),
"python": platform.python_version(),
"versions": {name: importlib.metadata.version(name)
for name in ["numpy", "pandas", "matplotlib"]},
}
(output / "results.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
report = (
f"Synthetic delivery analysis: {audit['clean']} valid rows.\n"
f"B minus A mean duration: {effect:.2f} minutes.\n"
f"95% percentile bootstrap interval: [{interval[0]:.2f}, {interval[1]:.2f}].\n"
"The bootstrap assumes independent, exchangeable rows within each route.\n"
"Data is generated for teaching; no real-world causal conclusion follows.\n"
"Distance differences and the small sample limit a simple route comparison.\n"
)
(output / "report.txt").write_text(report, encoding="utf-8")
print(audit)
print("Created analysis-output with data, audit, plots and report")
if __name__ == "__main__":
main()python analysis.pyExpected output
{'raw': 32, 'duplicates': 1, 'invalid_nonduplicates': 1, 'clean': 30}
Created analysis-output with data, audit, plots and reportThe numeric effect and interval are computed into results.json and report.txt by your own run. No particular decimal result is claimed here. A fixed seed helps repeat the configured run; versions and the raw checksum identify the actual evidence more precisely.
Add focused checks before interpreting the result
import numpy as np
import pandas as pd
from analysis import clean_data, estimate_difference, generate_data
def test_generation_and_audit():
raw = generate_data()
before = raw.copy(deep=True)
clean, rejected, audit = clean_data(raw)
assert audit == {"raw": 32, "duplicates": 1,
"invalid_nonduplicates": 1, "clean": 30}
assert len(rejected) == 2
assert clean["delivery_id"].is_unique
assert clean.groupby("route").size().to_dict() == {"A": 15, "B": 15}
pd.testing.assert_frame_equal(raw, before)
def test_interval_is_finite_and_ordered():
clean, _, _ = clean_data(generate_data())
effect, interval = estimate_difference(clean)
assert np.isfinite(effect)
assert interval.shape == (2,)
assert np.isfinite(interval).all()
assert interval[0] <= interval[1]python -m pytest -q test_analysis.pyExpected result: two passing tests. These structural checks do not establish statistical coverage or causal validity. Add an invalid route and a conflicting ID as separate tests; the latter should raise rather than silently select a record.
Guided review: follow one number back to its source
Open report.txt and choose the estimated difference. Recompute each route mean from clean.csv and verify their subtraction. Select a clean row and use source_row to locate its raw record. Inspect both quarantine reasons and the audit reconciliation. This small tracing exercise is more convincing than a report that merely says “data was cleaned.”
Inspect eda.png for three legible plots with units and a visible legend. Explain why a distribution, relationship and grouped mean answer different questions. If a route's distance distribution differs by chance, discuss that limitation before interpreting the raw mean comparison. Do not add a regression adjustment only to obtain a preferred answer; any expanded analysis needs its own stated target and checks.
Write a short README naming the synthetic generator, schema, cleaning policy, seeds, dependency versions, exact commands and output files. State that the current cleaner expects the generated numeric schema; it is not a general-purpose parser for arbitrary uploaded text. A future ingestion layer should validate and parse those types explicitly.
Optional advanced work: repeat the entire synthetic experiment across many independently generated datasets to study the interval procedure's coverage under a known generator. That is a new simulation study, not proof from one interval. Keep it separate from the core deliverable and report its assumptions and Monte Carlo variability.
Questions worth asking
Why retain raw.csv if the generator is available?
The generator describes how data was produced, while the saved raw bytes identify what this run actually analyzed. Keeping both, plus versions and a checksum, makes differences easier to investigate when code or random-generation behavior changes.
Does the checksum certify correctness?
No. It identifies a particular sequence of bytes and helps detect changes. Correctness still depends on the schema, cleaning rules, calculations, tests and interpretation. A perfectly recorded checksum can accompany a flawed analysis.
Why save quarantine records instead of only their count?
Counts reconcile the pipeline, but row-level records explain what was removed and why. Source-row identifiers allow review of each decision. That transparency matters when an exclusion materially changes a result or requires domain judgment.
Why are the bootstrap endpoints not hard-coded in the lesson?
They are generated numerical results that should come from an actual run in a recorded environment. The lesson supplies deterministic structural expectations and the computation, while the analysis bundle stores the observed endpoints honestly.
Can the route comparison justify changing a real delivery policy?
No. The data is artificial and the report is descriptive. Real decisions need appropriate data, design, uncertainty assessment and domain review. A synthetic capstone demonstrates analytical practice rather than evidence about a real organization.
What makes this bundle auditable?
A reader can trace a reported number through results, cleaned rows, raw records and generation code, and can rerun the documented commands. Explicit assumptions and limitations define where that evidence stops, instead of letting presentation imply more than was checked.
Practice, then compare your solution
1. Conflicting identity
Add a new row with an existing delivery_id but a different positive duration. What should happen?
Worked solution and reasoning
It is not an exact duplicate, so both candidate rows survive the duplicate flag. The uniqueness check then raises ValueError and requires review. Silently retaining the first would conceal a conflicting identity.
2. Report discipline
The observed interval includes zero. Write an appropriate conclusion.
Worked solution and reasoning
“The synthetic sample estimate is uncertain under the stated independent-row bootstrap procedure, with an interval including zero. This does not establish equivalence and does not support a real-world causal route claim.” Include the actual estimate and endpoints from your run.
Capstone completion rubric
Award equal attention to data lineage, numerical correctness, visual communication and honest inference. Completion means the bundle is reproducible in a fresh environment, every row is accounted for, the plots can be read without hidden context and the conclusion stays within the evidence. Keep the actual test and execution results with your project before moving into modeling.
Official documentation and next steps
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.