Data analysis · Intermediate · 22 min
Publish the energy analysis as a reproducible report
By Padding · Updated 18 Nov 2026
Python 3.15.2 · pandas 3.1.1 · matplotlib 3.11.2 · nbconvert 7.17.2 · ipykernel 7.4.0 · jupytext 1.19.7 · uv 0.13 (checked on python:3.15-slim)
You will turn the African electricity analysis into a Jupyter notebook that opens with its findings and caveats, build it into an HTML report with nbconvert, pin every package in uv.lock, prove it rebuilds the same numbers from the raw file in a fresh folder, and then clean up the series project.
On this page
Seven parts of work now sit in ~/energy-demo: a pinned raw file, a dozen scripts, tables in clean/ and summary/, charts and a long notes.md. That is enough for you to trust the results. It is not enough for anyone else. A colleague cannot tell which script to run first, a manager will not read code, and in a year even you will not remember whether the chart in your slides came from the final version of the table.
This last part packs the analysis into one report that answers all three problems. It is a Jupyter notebook that starts with the findings and the caveats in plain words, then shows the method, the table and the chart underneath. It reads only the raw file, so it rebuilds every number from scratch each time it runs. Its last cell checks that the numbers typed into the summary still match the data, so the report cannot be published with a figure the data no longer supports. You build it into a single HTML file with nbconvert, pin every package with uv.lock, and prove it reproduces by rebuilding it in an empty folder.
Then, because this is the end of the series, you keep what is worth keeping and delete the rest.
Step 1 · Check your starting point and add the notebook tools
Start the way every part has: prove the raw file is the one the analysis was built on.
cd ~/energy-demo
uv run check_raw.pyThe report needs three more packages, and none of them is needed to run the analysis scripts, so add them as development dependencies with --dev:
- ipykernel is the Python kernel, the process that runs a notebook's cells.
- nbconvert runs a notebook from top to bottom without a browser and writes the result as HTML.
- jupytext converts between a notebook (
.ipynb, a JSON file) and a plain Python script with cell markers. You write and review the script; the notebook is generated from it.
cd ~/energy-demo
uv add --dev "ipykernel>=7.4,<7.5" "nbconvert>=7.17,<7.18" "jupytext>=1.19,<1.20"
uv run jupyter nbconvert --version
uv run jupytext --versionWhy a script and not a notebook you edit in JupyterLab? A .ipynb file stores outputs, images and execution counts alongside your code, so a one-word change to the text can show up as hundreds of changed lines in a review. A percent-format script holds only what you wrote, and jupytext turns it into a notebook in a second. You can still open and edit it in JupyterLab; the last step shows how to write your edits back.
Check it worked
check_raw.py prints OK for both files. The two version commands print 7.17.2 and 1.19.7, or later patch releases of each. pyproject.toml now has a [dependency-groups] section with a dev list holding the three packages.
Step 2 · Write the report with the findings first
A report for people who make decisions answers their question in the first screen: what changed, how sure you are, and what the numbers cannot tell them. Method and code come after, for the readers who want to check. So the notebook starts with one Markdown cell holding the findings, the caveats and the source, and the code follows.
The findings below are the series' main results from parts 4 to 6, rounded to whole numbers. The caveats come from the list you wrote in part 7. If your list in notes.md says more, or says it better, use your words; keep each caveat to one sentence a manager can repeat.
In the percent format, # %% starts a code cell and # %% [markdown] starts a Markdown cell whose lines begin with # `. Create `report.py:
cd ~/energy-demo
cat > report.py <<'NOTEBOOK'
# %% [markdown]
# # African electricity since 2000
#
# Electricity generation per person in Africa's five UN subregions, 2000 to 2024.
#
# ## Findings
#
# - **Northern Africa more than doubled its generation per person**, from 804 kWh in 2000
# to 1,646 kWh in 2024, a rise of 105%.
# - **Southern Africa is the only subregion where it fell**, from 3,989 to 3,462 kWh (down 13%).
# Its generation grew by 18%, but its population grew by 36%.
# - **Middle, Eastern and Western Africa ended close together**, between 217 and 235 kWh per
# person. Middle Africa rose from 128 kWh, the lowest of the five in 2000.
# - **The gap is still wide.** In 2024 Southern Africa generated about 16 times as much
# electricity per person as Western Africa.
# - Across all five subregions together, generation per person rose from 535 to 639 kWh.
#
# ## What this data cannot show
#
# - **Generation is not access.** These figures count electricity produced, divided by everyone
# who lives there. They say nothing about who is connected, or how often the power goes off.
# - **Regional figures follow the largest countries.** South Africa holds most of Southern
# Africa's people, so Southern Africa's trend is mostly South Africa's.
# - **Coverage shrinks at the end.** 56 countries report in 2000 but 51 in 2024; the missing ones
# are small, but regional totals for 2024 are slightly understated.
# - **One zero is probably a gap.** Lesotho reports 0 TWh for 2023 and 2024. It is counted as
# zero here, which changes Southern Africa's total by less than 1%.
# - **Start and end years matter.** Growth rates compare 2000 with 2024, the first and last full
# years in this release. Other years give other rates.
# - **Figures can be revised.** They combine Ember and Energy Institute data. This report uses one
# fixed release of the dataset, checked by its SHA-256 fingerprint.
#
# ## Source and licence
#
# Data: Our World in Data energy dataset (github.com/owid/energy-data, commit f8de88a, 1 October
# 2026, the legacy release), with electricity data from Ember. Both are licensed CC BY 4.0.
# Subregions follow the UN M49 standard. Per-person figures are total generation divided by
# total population for each subregion and year, not an average of country figures.
# %%
import hashlib
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import FixedLocator, FuncFormatter, NullFormatter
RAW = Path("raw/owid-energy-data.csv")
RAW_SHA256 = "266f2e2baad7975351bc9bb4aa061d22b1da9fe4c47d51d2ac6071e01e171f76"
FIRST, LAST = 2000, 2024
OUT = Path("report")
OUT.mkdir(exist_ok=True)
digest = hashlib.sha256(RAW.read_bytes()).hexdigest()
assert digest == RAW_SHA256, f"{RAW} is not the pinned file: {digest}"
print(f"Raw file checked: {RAW}, SHA-256 {digest[:12]}...")
# %% [markdown]
# ## Method: subregion totals by year
# %%
M49 = {
"Northern Africa": "DZA EGY LBY MAR SDN TUN ESH",
"Eastern Africa": "IOT BDI COM DJI ERI ETH ATF KEN MDG MWI MUS MYT MOZ REU RWA SYC SOM SSD UGA TZA ZMB ZWE",
"Middle Africa": "AGO CMR CAF TCD COG COD GNQ GAB STP",
"Southern Africa": "BWA SWZ LSO NAM ZAF",
"Western Africa": "BEN BFA CPV CIV GMB GHA GIN GNB LBR MLI MRT NER NGA SHN SEN SLE TGO",
}
lookup = pd.DataFrame(
[(code, region) for region, codes in M49.items() for code in codes.split()],
columns=["iso_code", "subregion"],
)
raw = pd.read_csv(RAW)
countries = raw[raw["iso_code"].notna() & raw["year"].between(FIRST, LAST)]
countries = countries.merge(lookup, on="iso_code", how="inner", validate="m:1")
both = countries.dropna(subset=["electricity_generation", "population"])
region_year = both.groupby(["subregion", "year"], as_index=False).agg(
countries=("iso_code", "nunique"),
population=("population", "sum"),
generation_twh=("electricity_generation", "sum"),
renewables_twh=("renewables_electricity", "sum"),
)
region_year["kwh_per_person"] = region_year["generation_twh"] * 1e9 / region_year["population"]
region_year["renewables_share_pct"] = (
region_year["renewables_twh"] / region_year["generation_twh"] * 100
)
assert len(region_year) == 5 * (LAST - FIRST + 1), len(region_year)
region_year.to_parquet(OUT / "region_year.parquet", index=False)
print(f"{len(region_year)} rows: 5 subregions x {LAST - FIRST + 1} years")
# %%
wide = region_year.pivot(index="subregion", columns="year")
h = pd.DataFrame({
"kwh_2000": wide["kwh_per_person"][FIRST],
"kwh_2024": wide["kwh_per_person"][LAST],
"kwh_change_pct": (wide["kwh_per_person"][LAST] / wide["kwh_per_person"][FIRST] - 1) * 100,
"generation_change_pct": (wide["generation_twh"][LAST] / wide["generation_twh"][FIRST] - 1) * 100,
"population_change_pct": (wide["population"][LAST] / wide["population"][FIRST] - 1) * 100,
"countries_2000": wide["countries"][FIRST],
"countries_2024": wide["countries"][LAST],
}).sort_values("kwh_2024", ascending=False)
h.round(1).to_csv(OUT / "headlines.csv")
totals = region_year.groupby("year")[["generation_twh", "population"]].sum()
africa = totals["generation_twh"] * 1e9 / totals["population"]
print(f"All five subregions: {africa[FIRST]:,.0f} kWh per person in {FIRST}, "
f"{africa[LAST]:,.0f} in {LAST}")
h.round(1)
# %% [markdown]
# ## Generation per person by subregion
# %%
COLOURS = { # Okabe-Ito, the same colours as the part 6 charts
"Northern Africa": "#E69F00",
"Western Africa": "#0072B2",
"Middle Africa": "#009E73",
"Eastern Africa": "#D55E00",
"Southern Africa": "#CC79A7",
}
CREDIT = ("Source: Our World in Data energy dataset (github.com/owid/energy-data, commit f8de88a), "
"electricity data from Ember. CC BY 4.0.")
order = list(h.index)
fig, axes = plt.subplots(2, 3, figsize=(8, 4.8), sharex=True, sharey=True)
for ax, region in zip(axes.flat, order):
for other, part in region_year.groupby("subregion"):
if other != region:
ax.plot(part["year"], part["kwh_per_person"], color="#d9dce1", linewidth=1)
part = region_year[region_year["subregion"] == region]
ax.plot(part["year"], part["kwh_per_person"], color=COLOURS[region], linewidth=2)
ax.annotate(f"{h.loc[region, 'kwh_2024']:,.0f}", (LAST, h.loc[region, "kwh_2024"]),
xytext=(4, 0), textcoords="offset points", va="center", fontsize=8)
ax.set_title(region, loc="left", fontsize=9)
ax.set_yscale("log")
ax.set_ylim(100, 6000)
ax.set_xlim(FIRST, LAST)
ax.set_xticks([2000, 2010, 2020])
ax.yaxis.set_major_locator(FixedLocator([100, 200, 500, 1000, 2000, 5000]))
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:,.0f}"))
ax.yaxis.set_minor_formatter(NullFormatter())
ax.spines[["top", "right"]].set_visible(False)
axes[1, 2].set_visible(False)
axes[0, 2].xaxis.set_tick_params(labelbottom=True)
for ax in axes[:, 0]:
ax.set_ylabel("kWh per person (log scale)")
fig.suptitle("Electricity generation per person, 2000 to 2024", x=0.01, ha="left",
fontsize=11, fontweight="bold")
fig.tight_layout()
fig.text(0.01, -0.01, CREDIT, ha="left", va="top", fontsize=7, color="#6a707b")
plt.show()
moves = "; ".join(
f"{r} from {h.loc[r, 'kwh_2000']:,.0f} to {h.loc[r, 'kwh_2024']:,.0f}" for r in order
)
print("Chart description: five small line charts, one per African subregion, of electricity "
f"generation per person from {FIRST} to {LAST} on a shared log scale. In kWh per person: "
f"{moves}.")
# %% [markdown]
# ## Check the summary against the data
#
# The findings above are typed by hand. This cell stops the report from building if any of
# them no longer matches what the data says.
# %%
STATED = {
("Northern Africa", "kwh_2000"): 804,
("Northern Africa", "kwh_2024"): 1646,
("Northern Africa", "kwh_change_pct"): 105,
("Southern Africa", "kwh_2000"): 3989,
("Southern Africa", "kwh_2024"): 3462,
("Southern Africa", "kwh_change_pct"): -13,
("Southern Africa", "generation_change_pct"): 18,
("Southern Africa", "population_change_pct"): 36,
("Middle Africa", "kwh_2000"): 128,
("Middle Africa", "kwh_2024"): 235,
("Eastern Africa", "kwh_2024"): 230,
("Western Africa", "kwh_2024"): 217,
}
OTHER = {
"all subregions, kWh per person in 2000": (535, africa[FIRST]),
"all subregions, kWh per person in 2024": (639, africa[LAST]),
"countries reporting in 2000": (56, h["countries_2000"].sum()),
"countries reporting in 2024": (51, h["countries_2024"].sum()),
"highest over lowest in 2024": (16, h["kwh_2024"].max() / h["kwh_2024"].min()),
}
problems = []
for (region, column), stated in STATED.items():
actual = h.loc[region, column]
if abs(actual - stated) >= 0.5:
problems.append(f"{region} {column}: the summary says {stated}, the data says {actual:.1f}")
for label, (stated, actual) in OTHER.items():
if abs(actual - stated) >= 0.5:
problems.append(f"{label}: the summary says {stated}, the data says {actual:.1f}")
fell = list(h.index[h["kwh_change_pct"] < 0])
if fell != ["Southern Africa"]:
problems.append(f"only Southern Africa fell: the data says {fell}")
assert not problems, "\n".join(problems)
print(f"All {len(STATED) + len(OTHER) + 1} claims in the summary match the data.")
NOTEBOOK
grep -c '^# %%' report.pyA few choices in the script are deliberate:
- It reads only
raw/. It does not loadclean/orsummary/, so it cannot pick up a stale table from an earlier run. The subregion lookup and the ratio-of-sums rule are the same as in parts 3 and 4. - It checks the checksum first. If the raw file is not the pinned one, the report stops before it computes anything.
- It writes two small outputs to
report/: the regional table as Parquet and the headline numbers as CSV. The next steps use them to compare runs. - It prints a description under the chart. nbconvert cannot know what a chart shows, so the written description is what a screen reader user, or someone whose images did not load, gets instead.
- The last cell holds every number from the summary. Edit the findings and you edit
STATEDin the same commit.
Check it worked
grep -c prints 9: four Markdown cells and five code cells. Open report.py in your editor and read the first 45 lines as if you were the manager: you should learn the answer, the main caveats and the source without reading any code.
Step 3 · Run the notebook top to bottom into an HTML report
Convert the script into a notebook, then let nbconvert run it in a fresh kernel and save the result:
cd ~/energy-demo
uv run jupytext --to ipynb report.py
uv run jupyter nbconvert --to html --execute --no-input \
--ExecutePreprocessor.kernel_name=python3 --ExecutePreprocessor.timeout=300 \
--output-dir report report.ipynb
ls reportWhat each option does:
--executeruns every cell in order in a new kernel, the way a reader's fresh copy would, instead of using whatever outputs happen to be saved. A notebook that only works because you ran cell 7 before cell 4 fails here.--no-inputleaves the code out of the HTML and keeps the Markdown and the outputs. That suits readers who want the answer; anyone who wants the code hasreport.py.kernel_name=python3runs the cells with the Python in this project's.venv, where pandas and matplotlib are installed.timeout=300allows each cell up to five minutes, plenty for a 9 MB CSV on a slow laptop.
If any cell raises an error, nbconvert stops, prints the traceback and writes no HTML, so a half-run report never reaches anyone.
Now check the report contains what it should, without opening a browser:
cd ~/energy-demo
cat > check_report.py <<'PY'
from pathlib import Path
html = Path("report/report.html").read_text(encoding="utf-8")
checks = {
"findings before the chart": 0 <= html.find("Findings") < html.find("Generation per person by subregion"),
"caveats included": "What this data cannot show" in html,
"credit line included": all(s in html for s in ("Our World in Data", "Ember", "CC BY 4.0")),
"chart embedded in the file": 'src="data:image/png;base64,' in html,
"chart description printed": "Chart description:" in html,
"code left out": "import pandas" not in html,
"summary check passed": "claims in the summary match the data" in html,
}
for label, ok in checks.items():
print("OK " if ok else "FAIL", label)
print(f"report.html is {len(html.encode()) // 1024} KB")
raise SystemExit(0 if all(checks.values()) else 1)
PY
uv run check_report.py
cat report/headlines.csvThe chart sits inside the HTML as an embedded image, and the styles are in the file too, so the report is one file you can attach to an email or send in a messaging app. Readers on prepaid mobile data download it once and can read it offline afterwards.
Check it worked
ls report lists headlines.csv, region_year.parquet and report.html. check_report.py prints seven OK lines and the size of the file. headlines.csv has a header and five rows, starting with Southern Africa,3988.6,3461.9,-13.2,18.2,36.2,5,5 and ending with Western Africa. Open report/report.html in a browser: the title, findings and caveats come first, then the method output, the table, the five-panel chart with its source line and description, and a last line that reads All 18 claims in the summary match the data.
Step 4 · Check the report agrees with your earlier tables
The notebook rebuilt the regional table from the raw file on its own. Part 4 built it with separate scripts. If the two disagree, one of them has a bug, and you want to know before anyone reads the report:
cd ~/energy-demo
cat > compare_with_part4.py <<'PY'
import pandas as pd
keys = ["subregion", "year"]
report = pd.read_parquet("report/region_year.parquet").sort_values(keys).reset_index(drop=True)
part4 = pd.read_parquet("summary/region_year.parquet").sort_values(keys).reset_index(drop=True)
columns = ["subregion", "year", "countries", "population", "generation_twh", "kwh_per_person"]
pd.testing.assert_frame_equal(report[columns], part4[columns], check_dtype=False)
print(f"report and part 4 agree on {len(report)} rows and {len(columns)} columns")
PY
uv run compare_with_part4.pyassert_frame_equal compares every value and raises an error naming the first column that differs. Floating-point values are compared with a small tolerance, so a difference in the last decimal place from summing in another order does not count as a disagreement.
Check it worked
The script prints report and part 4 agree on 125 rows and 6 columns. If you changed a rule in part 4, such as how zeros are handled, the script fails and names the column. Decide which version is right, fix the other, and write the decision in notes.md.
Step 5 · Watch the summary check stop a wrong report
The summary check only earns its place if it fails when it should. Make a copy of the report with the end year changed to 2023, which is the kind of edit someone makes when they want "the latest complete year", and forget to update the findings. The copy also writes its tables to a separate report_wrong/ folder, so the good files in report/ stay as they are:
cd ~/energy-demo
cat > break_report.py <<'PY'
from pathlib import Path
text = Path("report.py").read_text()
changes = {
"FIRST, LAST = 2000, 2024": "FIRST, LAST = 2000, 2023",
'OUT = Path("report")': 'OUT = Path("report_wrong")',
}
for old, new in changes.items():
assert text.count(old) == 1, f"{old!r} was not found exactly once"
text = text.replace(old, new)
Path("report_wrong.py").write_text(text)
print("wrote report_wrong.py with LAST = 2023 and OUT = report_wrong")
PY
uv run break_report.py
uv run jupytext --to ipynb report_wrong.py
if uv run jupyter nbconvert --to html --execute --no-input \
--ExecutePreprocessor.kernel_name=python3 report_wrong.ipynb > build.log 2>&1; then
echo "the wrong report was built; check the last cell of report.py"
false
else
echo "build stopped, as it should"
fi
grep -E 'the summary says -?[0-9]+, the data says' build.log | head -n 3The pattern matches only lines with a number after the summary says, so it picks out the mismatches from the error message and skips the copy of the cell's source that nbconvert prints above the traceback.
Delete the broken copy, its notebook, its output folder, the log and the helper script:
cd ~/energy-demo
rm report_wrong.py report_wrong.ipynb build.log break_report.py
rm -rf report_wrongThe data for 2023 is real and complete, so every cell runs until the last one. There the 2023 values no longer match the numbers typed into the findings, and the assertion lists each mismatch.
Check it worked
You see build stopped, as it should, followed by up to three lines like Northern Africa kwh_2024: the summary says 1646, the data says ... with the 2023 value. No report_wrong.html was written. After the cleanup command the copies, the report_wrong/ folder and the log are gone. Your real report.py is unchanged, and report/ still holds the 2024 files: headlines.csv still starts with Southern Africa,3988.6,3461.9.
Step 6 · Pin the environment with uv.lock
Every uv add since part 1 has updated uv.lock, a file that records the exact version and checksum of every package in the project, including the dozens that pandas, matplotlib and nbconvert pull in. pyproject.toml says what you asked for (pandas>=3.1,<3.2); uv.lock says what you got (pandas 3.1.1, built from one particular file).
Look at a few of the locked versions, then confirm the lock matches pyproject.toml:
cd ~/energy-demo
grep -A1 -E '^name = "(pandas|matplotlib|nbconvert|ipykernel|jupytext)"$' uv.lock
uv sync --locked--locked makes uv refuse to run if pyproject.toml has changed since the lock was written, instead of quietly updating the lock. Use it whenever you rebuild a report someone else will rely on: a silent upgrade is exactly the kind of change that moves a number.
The files someone needs to rebuild the report are few: report.py, check_raw.py, pyproject.toml, uv.lock and .python-version. The raw data is not among them, because anyone can download it again from the pinned commit and check_raw.py proves it is the same file. Put those five files under version control. Leave out .venv/, report.ipynb and report/, which are all rebuilt.
Check it worked
grep prints each package name with a version = ` line under it, such as `version = "3.1.1" for pandas and version = "7.17.2" for nbconvert. uv sync --locked finishes without an error and without installing anything new, because the environment already matches the lock.
Step 7 · Rebuild the report from the raw file in an empty folder
Reproducible means someone else gets the same result. The nearest test you can run alone is to copy only the files from the last step, plus the raw data, into an empty folder, and build the report there. If the report depends on anything else in ~/energy-demo, such as a table from an earlier part or a package you installed by hand, this run fails:
cd ~/energy-demo
RERUN=$(mktemp -d)
cp -R raw check_raw.py report.py pyproject.toml uv.lock .python-version "$RERUN"/
cd "$RERUN"
ls -A
uv sync --locked
uv run check_raw.py
uv run jupytext --to ipynb report.py
uv run jupyter nbconvert --to html --execute --no-input \
--ExecutePreprocessor.kernel_name=python3 --output-dir report report.ipynb
cmp report/headlines.csv ~/energy-demo/report/headlines.csv
echo "headlines.csv is identical in both folders"
cd ~/energy-demo
rm -rf "$RERUN"mktemp -d makes a new empty folder with a unique name in your system's temporary directory, and rm -rf "$RERUN" deletes it at the end. uv sync --locked builds a new .venv from the lock. It reuses packages from uv's cache, so on prepaid data this step costs almost nothing; on a new machine it downloads the same versions.
The test compares headlines.csv, not report.html. The HTML can differ between runs in ways that do not matter, such as embedded image bytes. The headline numbers must not.
Check it worked
ls -A shows only the six items you copied, including the hidden .python-version. check_raw.py prints OK twice, nbconvert writes report/report.html in the new folder, cmp prints nothing (it only speaks when files differ), and the last line reads headlines.csv is identical in both folders.
Step 8 · Keep the report kit and clean up the series
Record what this part produced in notes.md:
cd ~/energy-demo
cat >> notes.md <<'MD'
## Part 8: report
- report.py is the report source (jupytext percent format). Build it with:
uv run jupytext --to ipynb report.py
uv run jupyter nbconvert --to html --execute --no-input --ExecutePreprocessor.kernel_name=python3 --output-dir report report.ipynb
- The report reads only raw/owid-energy-data.csv, checks its SHA-256 and rebuilds the regional table.
It matches summary/region_year.parquet from part 4 on all 125 rows.
- Its last cell checks the 18 claims in the findings against the data; a changed number stops the build.
- Rebuilt in an empty folder with uv sync --locked: identical headlines.csv.
- To rebuild: report.py, check_raw.py, pyproject.toml, uv.lock, .python-version, and the raw file
from commit f8de88a.
MD
tail -n 12 notes.mdCopy the report and the files needed to rebuild it into a folder of their own, ~/energy-report. This is the kit to share or keep:
cd ~/energy-demo
mkdir -p ~/energy-report
cp report/report.html report/headlines.csv report.py check_raw.py pyproject.toml uv.lock .python-version notes.md ~/energy-report/
ls -A ~/energy-reportIf you prefer to edit the report in a notebook interface, run JupyterLab for this project without adding it to the lock, then write your changes back to the script with jupytext:
uv run --with "jupyterlab>=4.6,<4.7" jupyter lab report.ipynb
uv run jupytext --to py:percent report.ipynbThe next command deletes ~/energy-demo and everything in it: the raw download, the clean and summary tables, the charts from part 6 and all the scripts. Check that ~/energy-report holds what you want to keep, and copy anything else you want, such as the charts/ folder, before you run it:
cd ~
rm -rf ~/energy-demo
ls -d ~/energy-demo 2>/dev/null || echo "~/energy-demo is gone"
uv cache pruneuv cache prune removes cache entries that no project uses any more. It leaves the rest of the cache alone, so your other uv projects are unaffected.
Check it worked
tail shows the new Part 8: report section. ls -A ~/energy-report lists eight files: .python-version, check_raw.py, headlines.csv, notes.md, pyproject.toml, report.html, report.py and uv.lock. After the delete, the shell prints ~/energy-demo is gone. To rebuild the report later, download the raw files into ~/energy-report/raw/ as in part 1, then run the two build commands from notes.md. When you no longer need the kit, rm -rf ~/energy-report removes the last thing this series created.
Next steps
- Turn the findings into a two-page note for decision makers, with a recommendation first: write up an analysis so decision makers act on it.
- Go deeper on lockfiles, Python versions and rebuilding on another machine: make an analysis reproducible with uv and a lockfile.
- Revisit the caveats the report carries and the tests behind them: check what the energy data can and cannot show, part 7 of this series.
- Start a new question in a notebook without the clutter: explore a dataset in JupyterLab.
Part of these paths
Related tutorials
- Check what the energy data can and cannot showYou will test each headline from the energy analysis against coverage changes, an older release of the data, population growth, missing measures and different start years, and end with a numbered caveats list in notes.md.
- Make a data analysis reproducible from raw data to resultsYou 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.
- Write up an analysis so decision-makers can act on itYou will turn a finished analysis into a two-page note that opens with the answer and a recommendation, backs it with three findings and one chart each, states its limits and your confidence in plain words, and has passed a peer review before it is sent.
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