Data analysis · Intermediate · 20 min
Make a data analysis reproducible from raw data to results
By Padding · Updated 18 Nov 2026
Python 3.15.2 · uv 0.13.10 · pandas 3.1.1 · NumPy 2.5.5 · GNU Make 4 (checked on python:3.15-slim)
You will have a small electricity analysis that rebuilds every table from a checksummed raw file with one make command, with every package pinned in uv.lock and a fixed random seed, proven by deleting the outputs and rebuilding them in a fresh folder.
On this page
An analysis is reproducible when someone else, or you in a year, can start from the raw data and get the same numbers without asking you anything. That rarely fails because of the maths. It fails because a package moved a minor version, a raw file was edited by hand and nobody noticed, a bootstrap gave slightly different bounds on every run, or the order in which to run five scripts lived only in your head.
In this tutorial you fix each of those in a small but real analysis: how fast electricity use per person grew in African countries between 2014 and 2024, using the Our World in Data energy file. You give the project a layout where raw data is read-only, pin every package in uv.lock, record where the raw file came from with its SHA-256 checksum, fix the random seed for a bootstrap, and write one make check command that rebuilds everything and compares it with recorded fingerprints. Then you prove it works the only way that counts: you delete the outputs, copy the project into an empty folder and rebuild it from scratch.
Everything lives in ~/repro-demo, which you delete at the end.
Step 1 · Lay out the project folders
Create a uv project with no build system (this is an analysis, not a package you will install elsewhere) and four folders, one per kind of file:
mkdir -p ~/repro-demo
cd ~/repro-demo
uv init --no-package --python 3.15 --name repro-demo
rm -f main.py
mkdir raw clean output src
ls -AEach folder has one rule:
raw/holds data exactly as you received it. Scripts read from it and never write to it.clean/holds data your scripts have filtered, renamed and tidied. It can always be rebuilt fromraw/.output/holds the results: tables, figures and summary numbers. It can always be rebuilt fromclean/.src/holds the scripts that do the rebuilding.
The rule that matters is the direction. Data only flows from raw/ to clean/ to output/, and only through code in src/. If you ever open a file in clean/ and fix a value by hand, the next rebuild silently undoes your fix, and nobody else can repeat it.
Check it worked
ls -A lists .python-version, README.md, clean, output, pyproject.toml, raw and src. If Git is installed, uv also creates .git and .gitignore. cat .python-version prints 3.15.
Step 2 · Pin uv and every package
Pin the version of uv itself first. A uv.toml file next to pyproject.toml is read as project configuration, and required-version makes any other uv version stop with an error instead of quietly behaving differently:
cd ~/repro-demo
cat > uv.toml <<'TOML'
required-version = ">=0.13,<0.14"
TOML
uv add "pandas>=3.1,<3.2" "numpy>=2.5,<2.6"
grep -A1 -E '^name = "(pandas|numpy)"$' uv.lock
uv sync --lockedThe two files now say different things on purpose. pyproject.toml says what the analysis accepts: any pandas 3.1. uv.lock says what you actually got: one exact version of pandas, NumPy and every package they depend on, with the SHA-256 of each file. Anyone who installs from the lock gets the same files.
--locked tells uv to use the lock exactly as it is and to stop with an error if pyproject.toml has changed since the lock was written. Without it, uv run and uv sync would update the lock for you, which is convenient while you work and wrong when you rebuild results. From here on, every command that runs the analysis uses --locked.
Check it worked
grep prints name = "numpy" with version = "2.5.5" under it, and name = "pandas" with version = "3.1.1" (or a later 3.1 release if one has come out since). uv sync --locked finishes without an error. Open uv.lock and search for hash = "sha256:: every package file has one.
Step 3 · Record the raw data source with a checksum
A file name says nothing about what is inside. Two people can both have owid-energy-data.csv and be working from different data. Record each raw file in sources.toml: where it came from, under what licence, when you got it and its SHA-256 checksum. The URL points at a fixed Git commit, not the latest version, so it always returns the same bytes.
cd ~/repro-demo
cat > sources.toml <<'TOML'
# Every file in raw/ is listed here. Never edit a file in raw/ by hand:
# add a new source, or replace a pinned URL and its sha256 together.
[[source]]
file = "raw/owid-energy-data.csv"
url = "https://raw.githubusercontent.com/owid/energy-data/f8de88a4f6f9cab44f1cf606047cbd6c4414042c/owid-energy-data.csv"
sha256 = "266f2e2baad7975351bc9bb4aa061d22b1da9fe4c47d51d2ac6071e01e171f76"
publisher = "Our World in Data"
licence = "CC BY 4.0"
retrieved = "2026-11-26"
TOMLNow write a script that downloads any missing source, refuses a file whose checksum is wrong, and makes the file read-only:
cd ~/repro-demo
cat > src/raw_data.py <<'PY'
"""Fetch and check the raw files listed in sources.toml.
uv run --locked src/raw_data.py fetch download missing files, then check all
uv run --locked src/raw_data.py check check every file against its sha256
uv run --locked src/raw_data.py hash FILE print a new file's sha256 for sources.toml
"""
import hashlib
import shutil
import sys
import tomllib
import urllib.request
from pathlib import Path
def sha256(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def sources():
with open("sources.toml", "rb") as f:
return tomllib.load(f)["source"]
def fetch():
for source in sources():
path = Path(source["file"])
if path.exists():
continue
path.parent.mkdir(parents=True, exist_ok=True)
part = path.with_name(path.name + ".part")
print(f"downloading {source['url']}")
with urllib.request.urlopen(source["url"], timeout=60) as response, open(part, "wb") as out:
shutil.copyfileobj(response, out)
if sha256(part) != source["sha256"]:
part.unlink()
sys.exit(f"{path}: the download does not match the sha256 in sources.toml")
part.chmod(0o444)
part.rename(path)
def check():
problems = 0
for source in sources():
path = Path(source["file"])
if not path.exists():
print(f"MISSING {path}")
problems += 1
elif sha256(path) != source["sha256"]:
print(f"CHANGED {path}")
problems += 1
else:
print(f"OK {path}")
if path.stat().st_mode & 0o222:
print(f" {path} is writable; run: chmod a-w {path}")
if problems:
sys.exit(f"{problems} raw file(s) missing or changed")
command = sys.argv[1] if len(sys.argv) > 1 else "check"
if command == "fetch":
fetch()
check()
elif command == "check":
check()
elif command == "hash":
print(sha256(sys.argv[2]))
else:
sys.exit(__doc__)
PY
uv run --locked src/raw_data.py fetch
ls -l rawThe download is about 9 MB. It happens once: fetch skips any file that is already there, so on prepaid mobile data you pay for it a single time, not on every rebuild. For your own data, put the file in raw/, run uv run --locked src/raw_data.py hash raw/<file> (replace <file> with its name) and copy the result into a new [[source]] entry. For a file that has no stable URL, such as a survey export someone emailed you, write where it came from in url anyway ("email from the field team, 3 March") so the checksum still ties the analysis to that exact file.
Check it worked
The script prints downloading https://raw.githubusercontent.com/... and then OK raw/owid-energy-data.csv. ls -l raw shows the file with permissions -r--r--r-- and a size of 9229369 bytes. If you run uv run --locked src/raw_data.py check again, it prints the same OK line without downloading anything.
Step 4 · Write the cleaning script
The cleaning script reads only raw/ and writes only clean/. It keeps the 2000 to 2024 rows for countries in Africa (the UN M49 list of codes), keeps five columns in a fixed order, drops rows with no electricity figure and sorts the result. The sort matters: rows written in a fixed order give a byte-identical file on every run, which is what lets you compare checksums later.
cd ~/repro-demo
cat > src/clean.py <<'PY'
"""raw/owid-energy-data.csv -> clean/africa_electricity.csv"""
from pathlib import Path
import pandas as pd
# UN M49 codes for the five African subregions.
AFRICA = """
DZA EGY LBY MAR SDN TUN ESH
IOT BDI COM DJI ERI ETH ATF KEN MDG MWI MUS MYT MOZ REU RWA SYC SOM SSD UGA TZA ZMB ZWE
AGO CMR CAF TCD COG COD GNQ GAB STP
BWA SWZ LSO NAM ZAF
BEN BFA CPV CIV GMB GHA GIN GNB LBR MLI MRT NER NGA SHN SEN SLE TGO
""".split()
columns = ["country", "iso_code", "year", "population", "per_capita_electricity"]
df = pd.read_csv("raw/owid-energy-data.csv", usecols=columns)[columns]
df = df[df["iso_code"].isin(AFRICA) & df["year"].between(2000, 2024)]
df = df.rename(columns={"per_capita_electricity": "kwh_per_person"})
df = df.dropna(subset=["kwh_per_person"]).sort_values(["iso_code", "year"])
Path("clean").mkdir(exist_ok=True)
df.to_csv("clean/africa_electricity.csv", index=False)
print(f"wrote clean/africa_electricity.csv: {len(df)} rows, {df['iso_code'].nunique()} countries")
PY
uv run --locked src/clean.py
head -n 3 clean/africa_electricity.csvNotice what the script does not do: it never opens raw/ for writing, and it creates clean/ itself, so deleting the folder is always safe.
Check it worked
The script prints wrote clean/africa_electricity.csv: 1393 rows, 57 countries. head shows the header country,iso_code,year,population,kwh_per_person and the first two rows, for Angola in 2000 and 2001.
Step 5 · Analyse the data with a fixed random seed
The analysis computes each country's average yearly growth in electricity use per person from 2014 to 2024, then uses a bootstrap to put a 95% interval around the mean growth across countries. A bootstrap resamples the countries thousands of times at random, so without a seed its bounds change a little on every run. That is enough to make a careful reader doubt every other number in your report.
NumPy's default_rng() with no argument takes fresh randomness from the operating system each time. Give it a seed and it produces the same sequence every time, on every machine, for a given NumPy version. Put the seed in the code and in the output, so anyone reading the result knows how to repeat it:
cd ~/repro-demo
cat > src/analyse.py <<'PY'
"""clean/africa_electricity.csv -> output/growth_by_country.csv, output/summary.json"""
import argparse
import json
from pathlib import Path
import numpy as np
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=20261118)
parser.add_argument("--resamples", type=int, default=10_000)
parser.add_argument("--out", default="output")
args = parser.parse_args()
START, END = 2014, 2024
df = pd.read_csv("clean/africa_electricity.csv")
wide = (
df[df["year"].isin([START, END])]
.pivot(index="country", columns="year", values="kwh_per_person")
.dropna()
)
wide = wide[wide[START] > 0]
rate = ((wide[END] / wide[START]) ** (1 / (END - START)) - 1) * 100
growth = pd.DataFrame({
f"kwh_{START}": wide[START],
f"kwh_{END}": wide[END],
"yearly_growth_pct": rate,
}).sort_values("yearly_growth_pct", ascending=False, kind="stable")
rng = np.random.default_rng(args.seed)
values = rate.to_numpy()
picks = rng.integers(0, len(values), size=(args.resamples, len(values)))
means = values[picks].mean(axis=1)
low, high = np.percentile(means, [2.5, 97.5])
summary = {
"countries": len(values),
"period": f"{START}-{END}",
"median_yearly_growth_pct": round(float(np.median(values)), 2),
"mean_yearly_growth_pct": round(float(values.mean()), 2),
"mean_ci95_low": round(float(low), 2),
"mean_ci95_high": round(float(high), 2),
"seed": args.seed,
"resamples": args.resamples,
}
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
growth.to_csv(out / "growth_by_country.csv", float_format="%.2f")
(out / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
print(f"wrote {out}/growth_by_country.csv and {out}/summary.json")
PY
uv run --locked src/analyse.py
cat output/summary.json
head -n 4 output/growth_by_country.csvTwo smaller choices also protect the result. kind="stable" keeps countries with equal growth in alphabetical order instead of an order that could change, and float_format="%.2f" writes numbers to a fixed precision, so a difference in the fifteenth decimal place can never change the file.
Now prove the seed does its job. Run the analysis twice more into a temporary folder, once with the same seed and once with a different one:
cd ~/repro-demo
TRY=$(mktemp -d)
uv run --locked src/analyse.py --out "$TRY/same"
uv run --locked src/analyse.py --seed 7 --out "$TRY/other"
cmp output/summary.json "$TRY/same/summary.json"
echo "same seed: identical summary"
if cmp -s output/summary.json "$TRY/other/summary.json"; then
echo "a different seed gave the same file; check that analyse.py uses args.seed"
false
else
echo "different seed: the interval moved"
fi
grep ci95 "$TRY/other/summary.json"
rm -rf "$TRY"Check it worked
summary.json shows "countries": 51, a median of about 1.64 and a mean of about 0.47 per cent a year, the two interval bounds either side of the mean, and "seed": 20261118. The growth table starts with Guinea, Congo and Benin. The second command prints same seed: identical summary, then different seed: the interval moved, followed by the seed 7 bounds, at least one of which differs slightly from yours. The median and mean do not move, because they do not depend on the random draws.
The gap between median and mean is worth a note in your write-up: a few countries where use per person fell pull the mean down.
Step 6 · Rebuild everything with one make command
Four scripts that must run in the right order are four chances to get it wrong. A Makefile writes the order down once, and only reruns the steps whose inputs have changed. Install GNU Make on Ubuntu (on macOS, xcode-select --install provides it):
sudo apt-get update
sudo apt-get install -y make
make --version | head -n 1Each rule in the Makefile names a file, the files it is built from, and the command that builds it. uv.lock is listed as an input to both the cleaning and the analysis, so changing a package version rebuilds the results. The lines that run commands start with a tab character, not spaces. If your editor or the copy turns the tab into spaces, make stops with missing separator.
cd ~/repro-demo
cat > Makefile <<'MAKE'
# Rebuild every result from raw data: make all
# Rebuild and compare with the recorded fingerprints: make check
UV_RUN := uv run --locked
RAW := raw/owid-energy-data.csv
CLEAN := clean/africa_electricity.csv
RESULT := output/summary.json
.PHONY: all check wipe
all: $(RESULT)
$(RAW):
$(UV_RUN) src/raw_data.py fetch
$(CLEAN): $(RAW) src/clean.py uv.lock
$(UV_RUN) src/raw_data.py check
$(UV_RUN) src/clean.py
$(RESULT): $(CLEAN) src/analyse.py uv.lock
$(UV_RUN) src/analyse.py
check: all
$(UV_RUN) src/fingerprint.py | diff expected-results.txt -
@echo "all outputs match expected-results.txt"
# Deletes clean/ and output/ only. raw/ is never touched.
wipe:
rm -rf clean output
MAKE
make allThe raw file has no inputs in the Makefile, so make only fetches it when it is missing. It never redownloads a file you already have.
Check it worked
make --version prints GNU Make 4 followed by a minor version. make all prints make: Nothing to be done for 'all'., because every output is newer than everything it was built from. Now change the analysis script's date without changing its content, and ask make what it would do:
cd ~/repro-demo
touch src/analyse.py
make -n allmake -n prints the commands without running them: one line, uv run --locked src/analyse.py. The cleaning step is skipped because its inputs have not changed. Run make all to bring the outputs up to date:
cd ~/repro-demo
make allStep 7 · Delete the outputs and rebuild them
Record a fingerprint of every file in clean/ and output/. This is what "the same result" means from now on: the same bytes, checked by SHA-256, not "the numbers look about right".
cd ~/repro-demo
cat > src/fingerprint.py <<'PY'
"""Print the sha256 of every file in clean/ and output/, in a fixed order."""
import hashlib
from pathlib import Path
for folder in ("clean", "output"):
for path in sorted(Path(folder).rglob("*")):
if path.is_file():
print(hashlib.sha256(path.read_bytes()).hexdigest(), path.as_posix())
PY
uv run --locked src/fingerprint.py > expected-results.txt
cat expected-results.txtNow delete every output and rebuild with the one command:
cd ~/repro-demo
make wipe
ls
make checkmake check depends on all, so it first notices that clean/ and output/ are gone and rebuilds them in order: check the raw file, clean, analyse. Then it fingerprints the new files and compares them with expected-results.txt. diff prints nothing when the two match, and make stops with an error naming the changed file when they do not.
When you deliberately change the analysis later, such as a new year range, rebuild, look at the new results, and then rewrite expected-results.txt with the same fingerprint.py command. That turns every change in the results into a decision someone made, not an accident.
Check it worked
expected-results.txt has three lines, each a 64-character hash followed by a path: clean/africa_electricity.csv, output/growth_by_country.csv and output/summary.json. After make wipe, ls shows no clean or output folder. make check prints the three script commands, ends with all outputs match expected-results.txt and exits without an error.
Step 8 · Rebuild from scratch in a fresh folder
Your own folder still has a .venv, a downloaded raw file and a uv cache. The real test is whether the analysis rebuilds from only the files you would put under version control. List them, and keep everything that is rebuilt out of Git:
cd ~/repro-demo
cat > .gitignore <<'TXT'
.venv/
raw/
clean/
output/
TXT
cat > README.md <<'MD'
# repro-demo
Yearly growth in electricity use per person in African countries, 2014 to 2024.
Rebuild every result from the raw data and check it against expected-results.txt:
make check
Needs uv 0.13 and GNU Make. The raw file is downloaded from the pinned URL in
sources.toml and checked against its sha256. Never edit raw/ by hand.
MDraw/ stays out of Git because sources.toml already pins it: the URL and the checksum together say exactly which file to use, and make fetches it. If your raw data cannot be downloaded again, such as a one-off export, keep it somewhere backed up and keep the checksum in sources.toml all the same.
Now copy only the files Git would hold into an empty folder and rebuild:
cd ~/repro-demo
FRESH=$(mktemp -d)
cp -R .gitignore .python-version README.md pyproject.toml uv.lock uv.toml sources.toml \
Makefile expected-results.txt src "$FRESH"/
cd "$FRESH"
ls -A
make check
cd ~/repro-demo
rm -rf "$FRESH"In the new folder there is no .venv and no raw file. uv run --locked creates a new environment from uv.lock, reusing package files from uv's cache where it can, and make downloads the raw file again (about 9 MB) and checks its checksum before anything reads it. On a slow or metered connection you can copy raw/ across with cp -Rp raw "$FRESH"/ before make check instead; the checksum test still runs.
Check it worked
ls -A lists only the ten items you copied. make check prints downloading https://raw.githubusercontent.com/..., OK raw/owid-energy-data.csv, the cleaning and analysis lines and, last, all outputs match expected-results.txt. That line is your proof: a folder with no history produced byte-identical results from the raw data.
Step 9 · Remove the demo
When you have finished, leave the project folder and delete it. The raw file is read-only, but rm -rf removes it because the folder itself is writable:
cd ~
rm -rf ~/repro-demo
uv cache pruneuv cache prune removes cached packages that no project uses any more. It keeps everything else in the cache, so your other projects are not affected.
Check it worked
ls ~/repro-demo reports No such file or directory.
Next steps
- Turn the analysis into a findings-first HTML report that rebuilds the same way in Publish the energy analysis as a reproducible report.
- Learn how targets, variables and
.PHONYwork in more depth in Automate tasks with a Makefile. - Explore data interactively without losing reproducibility in Explore a dataset in JupyterLab.
- See what else
pyproject.tomlanduv.lockcan hold in Package a Python project with uv and pyproject.toml.
Part of these paths
Related tutorials
- Package a Python project with uv and pyproject.tomlYou will turn a small currency-formatting module into an installable Python package with a src layout, a command-line entry point, an optional extra and a dev dependency group, then lock it, build a wheel and an sdist, and prove the wheel works in a clean environment.
- How to Automate Repeated Commands with a MakefileYou will write a Makefile that gives a project short, memorable commands (make check, make backup, make clean), learn how targets, prerequisites and variables work, and avoid the tab and .PHONY mistakes that trip up most first Makefiles.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials