Data analysis · Beginner · 20 min
Clean the energy data: countries, aggregates, gaps and units
By Padding · Updated 18 Nov 2026
python:3.15-slim (Debian 13) · Python 3.15.2 · pandas 3.1.1 · pyarrow 26.0.1
You will turn the raw OWID energy file into a tidy table of 55 African countries from 2000 to 2024, with clear column names, checked units and every cleaning decision written down in notes.md.
On this page
In part 1 you downloaded the Our World in Data (OWID) energy file and found out what it holds: one row per place and year, 130 columns, and a mix of countries and regional totals. Before you can compare African countries, you need a smaller, cleaner table with only the rows and columns this analysis uses.
This part is about scope and coverage, not messy text. You decide which rows are countries and which are aggregates, which columns to keep and what to call them, whether the units agree with each other, and which countries have enough years to compare. Each decision goes into notes.md, so anyone reading the analysis later can see what you removed and why. The result is clean/energy.parquet, the country table that part 3 gives subregions and part 6 charts.
Your raw file stays read-only. Every script reads from raw/ and writes somewhere else, so you can always rebuild the clean table from scratch.
Step 1 · Check your starting point and add pyarrow
Go to the project and confirm the raw file is the exact one from part 1. A different checksum means a different file, and none of the numbers below would match:
cd ~/energy-demo
uv run python -c "import hashlib, pathlib; print(hashlib.sha256(pathlib.Path('raw/owid-energy-data.csv').read_bytes()).hexdigest())"This part also reads the codebook, raw/owid-energy-codebook.csv. If you did not save it in part 1, download it from the same commit:
curl -fsSL -o raw/owid-energy-codebook.csv https://raw.githubusercontent.com/owid/energy-data/f8de88a4f6f9cab44f1cf606047cbd6c4414042c/owid-energy-codebook.csvThe clean table is saved as Parquet, a compact column-based file format that keeps data types (whole numbers stay whole numbers, text stays text). pandas writes Parquet through the pyarrow package, so add it:
uv add "pyarrow>=26.0,<27"
uv run python -c "import pandas, pyarrow; print(pandas.__version__, pyarrow.__version__)"Check it worked
The checksum is 266f2e2baad7975351bc9bb4aa061d22b1da9fe4c47d51d2ac6071e01e171f76, and the second command prints 3.1.1 26.0.1 or later patch releases of each. ls raw lists both CSV files.
Step 2 · Separate countries from aggregates
The file mixes two kinds of row. Countries carry an ISO 3166-1 alpha-3 code in iso_code, such as NGA for Nigeria. Aggregates such as World or Africa (Ember) have no code. If you add up a column without separating them, you count Nigeria once on its own and again inside every total that contains it.
Write scope.py to see how the two groups split:
cat > scope.py <<'PY'
import pandas as pd
df = pd.read_csv("raw/owid-energy-data.csv")
has_code = df["iso_code"].notna()
print("rows with an ISO code:", has_code.sum())
print("rows without one:", (~has_code).sum())
no_code = sorted(df.loc[~has_code, "country"].unique())
print("names without a code:", len(no_code))
print([name for name in no_code if "Africa" in name])
print([name for name in no_code if "(" not in name and "countries" not in name])
PY
uv run scope.pyThe name in brackets says whose definition of the region it is: (Ember), (EI) for the Energy Institute, (EIA) for the US Energy Information Administration. Plain Africa is OWID's own total. These regions do not all contain the same countries, which is one more reason never to mix them.
The last list is a warning about the rule "no code means aggregate". It holds continents and World, but also Kosovo, a country with no official ISO code, and former states such as USSR and Yugoslavia. None of them is in Africa, so the rule is safe here, but check it again before you reuse this code for another region.
Check it worked
The script prints 17265 rows with a code, 6112 without, 94 names without a code, a list of 14 Africa names starting with 'Africa', 'Africa (EI)', and a final list that includes 'Kosovo' and 'USSR'.
Step 3 · Narrow the rows to African countries since 2000
"African countries" needs a definition you can cite. This series uses the UN M49 standard, in which Africa (region code 002) has 60 entries, each with an alpha-3 code. Save them in a text file, one row per 15 codes:
cat > africa_m49_codes.txt <<'TXT'
AGO ATF BDI BEN BFA BWA CAF CIV CMR COD COG COM CPV DJI DZA
EGY ERI ESH ETH GAB GHA GIN GMB GNB GNQ IOT KEN LBR LBY LSO
MAR MDG MLI MOZ MRT MUS MWI MYT NAM NER NGA REU RWA SDN SEN
SHN SLE SOM SSD STP SWZ SYC TCD TGO TUN TZA UGA ZAF ZMB ZWE
TXTFilter on codes, never on names. The file spells Cote d'Ivoire and Reunion without accents, other sources write Côte d'Ivoire, Ivory Coast or a French or Portuguese name, and a name match silently drops whichever spelling you did not expect. Codes do not change with the language of the source.
cat > africa.py <<'PY'
from pathlib import Path
import pandas as pd
codes = Path("africa_m49_codes.txt").read_text().split()
df = pd.read_csv("raw/owid-energy-data.csv")
africa = df[df["iso_code"].isin(codes) & (df["year"] >= 2000)]
print("codes in the list:", len(codes))
print("codes found:", africa["iso_code"].nunique())
print("not in the file:", sorted(set(codes) - set(africa["iso_code"])))
print("rows:", len(africa))
print("years:", africa["year"].min(), "to", africa["year"].max())
PY
uv run africa.pyThe year filter starts at 2000 because that is where this series' question starts. The years: line shows the range the file holds for African countries from then on, and a later step counts how many countries report in each of the latest years.
Check it worked
The output says 60 codes in the list and 57 found. The three missing are ATF, IOT and MYT (the French Southern Territories, the British Indian Ocean Territory and Mayotte), which the file does not cover. There are 1414 rows from 2000 to 2025.
Step 4 · Keep the electricity columns and rename them
You need population, total generation, generation per person, demand, generation by source and the renewables share. That is 16 of the 130 columns, plus the three that identify a row. Put the list in its own module, energy_columns.py, so every script uses the same names. Each new name ends in its unit, so nobody has to guess later whether a number is TWh or kWh:
cat > energy_columns.py <<'PY'
# Columns kept from owid-energy-data.csv, and the names used from here on.
COLUMNS = {
"country": "country",
"iso_code": "iso_code",
"year": "year",
"population": "population",
"electricity_generation": "generation_twh",
"per_capita_electricity": "generation_kwh_per_person",
"electricity_demand": "demand_twh",
"coal_electricity": "coal_twh",
"gas_electricity": "gas_twh",
"oil_electricity": "oil_twh",
"nuclear_electricity": "nuclear_twh",
"hydro_electricity": "hydro_twh",
"solar_electricity": "solar_twh",
"wind_electricity": "wind_twh",
"biofuel_electricity": "bioenergy_twh",
"other_renewable_exc_biofuel_electricity": "other_renewable_twh",
"fossil_electricity": "fossil_twh",
"renewables_electricity": "renewables_twh",
"renewables_share_elec": "renewables_share_pct",
}
SOURCES = [
"coal_twh", "gas_twh", "oil_twh", "nuclear_twh", "hydro_twh",
"solar_twh", "wind_twh", "bioenergy_twh", "other_renewable_twh",
]
PYSOURCES lists the columns that, between them, should add up to total generation. Fossil and renewables totals are left out of it, because they are sums of the others.
Now read the unit and the source of each kept column from the codebook, rather than trusting the column name:
cat > units.py <<'PY'
import pandas as pd
from energy_columns import COLUMNS
book = pd.read_csv("raw/owid-energy-codebook.csv").set_index("column")
kept = book.loc[[c for c in COLUMNS if c not in ("country", "iso_code", "year")]]
for column, row in kept.iterrows():
ember = "Ember" in row["source"]
ei = "Energy Institute" in row["source"]
print(f"{column:40} {row['unit']:21} Ember={ember!s:5} EI={ei}")
PY
uv run units.pyCheck it worked
You see 16 lines. population is in people, every _electricity column and electricity_generation are in terawatt-hours (TWh), per_capita_electricity is in kilowatt-hours (kWh) (per person, as its description says) and renewables_share_elec is in %. Every electricity column names Ember as a source. Most also name the Energy Institute (EI=True): OWID combines the two. Write that down, because a column with two sources can change when either one is revised, and part 7 comes back to it.
Step 5 · Check that the units agree with each other
A codebook can be wrong, and a column can be mislabelled. Three columns can be rebuilt from others, so rebuild them and compare:
- Generation per person should equal total generation divided by population. One TWh is one billion kWh, so multiply by 1e9.
- The nine source columns should add up to total generation.
- The renewables share should equal renewables divided by the total, times 100.
cat > consistency.py <<'PY'
from pathlib import Path
import pandas as pd
from energy_columns import COLUMNS, SOURCES
codes = Path("africa_m49_codes.txt").read_text().split()
df = pd.read_csv("raw/owid-energy-data.csv", usecols=list(COLUMNS))
df = df[df["iso_code"].isin(codes) & (df["year"] >= 2000)].rename(columns=COLUMNS)
# 1 TWh is 1,000,000,000 kWh
per_person = df["generation_twh"] * 1e9 / df["population"]
gap = (per_person - df["generation_kwh_per_person"]).abs()
print("per person, largest gap (kWh):", round(gap.max(), 3))
sources_total = df[SOURCES].sum(axis=1, min_count=1)
gap = (sources_total - df["generation_twh"]).abs()
print("sum of sources, largest gap (TWh):", round(gap.max(), 3))
share = df["renewables_twh"] / df["generation_twh"] * 100
gap = (share - df["renewables_share_pct"]).abs()
print("renewables share, largest gap (points):", round(gap.max(), 3))
print("share range:", df["renewables_share_pct"].min(), "to", df["renewables_share_pct"].max())
PY
uv run consistency.pymin_count=1 makes a row with no source values at all sum to missing, not to 0, so an empty row does not look like a country that generated nothing.
Check it worked
The largest gaps are 0.001 kWh, 0.0 TWh and 0.001 percentage points, and shares run from 0.0 to 100.0. Gaps that small come from rounding in the CSV, so the units are what the codebook says. If a gap were near 1,000 or 1,000,000, a column would be in different units from its label.
Step 6 · Count the gaps by country and year
Now find out where data is missing. Look at it three ways: how many countries report each year, which columns have missing values, and which countries have the fewest years. Also look for zeros, because a zero can be a gap in disguise.
cat > gaps.py <<'PY'
from pathlib import Path
import pandas as pd
from energy_columns import COLUMNS
codes = Path("africa_m49_codes.txt").read_text().split()
df = pd.read_csv("raw/owid-energy-data.csv", usecols=list(COLUMNS))
df = df[df["iso_code"].isin(codes) & (df["year"] >= 2000)].rename(columns=COLUMNS)
by_year = df.groupby("year")["generation_twh"].count()
print("countries with generation, by year:")
print(by_year.tail(4).to_string())
missing = df.drop(columns=["country", "iso_code", "year"]).isna().sum()
print("missing values by column:")
print(missing[missing > 0].to_string())
window = df[df["year"].between(2000, 2024)]
years = window.groupby("country")["generation_twh"].count()
print("fewest years with generation, 2000-2024:")
print(years.sort_values().head(4).to_string())
zeros = df[df["generation_twh"] == 0]
print("zero generation:")
print(zeros[["country", "year", "population"]].to_string(index=False))
PY
uv run gaps.pyRead the output closely:
- 56 countries report in 2022 and 2023, 51 in 2024, and only 7 in 2025. The latest year is incomplete, and an Africa total for 2025 would be a total for seven countries.
generation_twhhas 14 missing values. All 14 belong to Western Sahara, which has rows for 24 years but generation for only 10.- South Sudan has 13 years, but no missing values. Its rows start in 2012, after independence in 2011, so the years before simply do not exist.
isna()cannot count rows that are not there: always count years per country as well. - Lesotho shows a total of exactly 0 TWh in 2023 and 2024, for more than two million people. The same file gives Lesotho 0.48 TWh of hydropower in 2022. A drop to zero is far more likely to be a gap in the source than a real event.
Some source columns, such as gas_twh and nuclear_twh, have more missing values than the total. The previous step showed the sources still add up to the total, so those gaps hide no electricity: that country reports no generation from that source.
Check it worked
You see the four year counts above, a list of missing values by column with generation_twh 14, the fewest-years list starting with Western Sahara 10 and South Sudan 13, and two zero rows, both Lesotho.
Step 7 · Decide what to keep and write the clean table
Turn what you found into rules, and put the rules in one script, clean.py, so the whole clean-up can be rerun from the raw file:
- Years: 2000 to 2024. 2025 has too few countries.
- Zeros: a total of exactly 0 TWh is treated as missing, with all the electricity columns in that row.
- Coverage: keep countries with generation in at least 20 of the 25 years. Twenty is a judgement, not a law: it keeps countries with one or two missing years and drops those that would make a trend appear or vanish when they join or leave the series.
- Aggregates: no aggregate goes in the country table. The
Africa (Ember)total is saved in its own file, because part 4 uses it to check your regional sums.
cat > clean.py <<'PY'
from pathlib import Path
import pandas as pd
from energy_columns import COLUMNS
FIRST, LAST = 2000, 2024 # 2025 has only 7 countries in this release
MIN_YEARS = 20 # of the 25 years in the window
codes = Path("africa_m49_codes.txt").read_text().split()
raw = pd.read_csv("raw/owid-energy-data.csv", usecols=list(COLUMNS))
raw = raw[list(COLUMNS)].rename(columns=COLUMNS)
in_window = raw["year"].between(FIRST, LAST)
electricity = [c for c in raw.columns if c not in ("country", "iso_code", "year", "population")]
# Countries: African M49 codes only, aggregates have no code and fall out here.
df = raw[raw["iso_code"].isin(codes) & in_window].copy()
# A total of exactly 0 TWh for a populated country is a missing value, not a fact.
zero = df["generation_twh"] == 0
df.loc[zero, electricity] = pd.NA
# Keep countries with enough years to compare.
years = df.groupby("iso_code")["generation_twh"].count()
keep = years[years >= MIN_YEARS].index
dropped = sorted(df.loc[~df["iso_code"].isin(keep), "country"].unique())
df = df[df["iso_code"].isin(keep)]
df["population"] = df["population"].round().astype("Int64")
df = df.sort_values(["iso_code", "year"]).reset_index(drop=True)
assert not df.duplicated(["iso_code", "year"]).any(), "one row per country and year"
assert df["year"].between(FIRST, LAST).all()
# The dataset's own Africa total, kept separately for checking sums later.
aggregate = raw[(raw["country"] == "Africa (Ember)") & in_window]
aggregate = aggregate.dropna(axis="columns", how="all").reset_index(drop=True)
Path("clean").mkdir(exist_ok=True)
df.to_parquet("clean/energy.parquet", index=False)
aggregate.to_parquet("clean/africa_ember.parquet", index=False)
print("zero totals set to missing:", int(zero.sum()))
print("dropped for coverage:", dropped)
print("countries kept:", df["iso_code"].nunique())
print("rows written:", len(df))
print("aggregate rows:", len(aggregate))
PY
uv run clean.pyA few details in the script matter. .copy() makes df its own table, so the later assignments change it and not raw. Int64 (capital I) is pandas' whole-number type that allows missing values, so population is stored as people, not as a decimal. The two assert lines stop the script before anything is written if a duplicate country-year or a stray year slips through. dropna(axis="columns", how="all") removes columns that are empty for the aggregate, such as population, which OWID does not give for Ember's regions.
Check it worked
The script reports 2 zero totals set to missing, drops South Sudan and Western Sahara, and keeps 55 countries in 1370 rows, with 25 aggregate rows. Now open the clean file with a separate script, the way later parts will:
cat > check_clean.py <<'PY'
import pandas as pd
df = pd.read_parquet("clean/energy.parquet")
print("shape:", df.shape)
print("years:", df["year"].min(), "to", df["year"].max())
print("countries:", df["iso_code"].nunique())
print("duplicate country-years:", df.duplicated(["iso_code", "year"]).sum())
lesotho = df[df["iso_code"] == "LSO"].tail(3)
print(lesotho[["year", "generation_twh", "hydro_twh"]].to_string(index=False))
PY
uv run check_clean.py
ls -l cleanIt prints a shape of (1370, 19), years 2000 to 2024, 55 countries, 0 duplicates, and Lesotho's last three rows: 0.48 for 2022, then NaN for 2023 and 2024. 55 countries times 25 years is 1375 rows: the 5 missing rows are 2024 for five countries whose data ends in 2023.
clean/energy.parquet is about 68 KB, against more than 9 MB for the raw CSV. If you share the analysis with colleagues on prepaid mobile data, or open it on an older laptop, send the Parquet file and the scripts, not the raw download.
Step 8 · Record every decision in notes.md
A clean table without its reasons is hard to trust. Anyone who sees 55 countries will ask where the other two went, and in six months that person may be you. Add a section to notes.md:
cat >> notes.md <<'MD'
## Cleaning decisions (part 2)
- Source: OWID energy-data, legacy release, commit f8de88a, file sha256 266f2e2b...1f76. Credit: Our World in Data and Ember, CC BY 4.0.
- Scope: African countries as defined by UN M49 (africa_m49_codes.txt, 60 codes). 57 are in the file; ATF, IOT and MYT are not.
- Countries only: rows without an ISO code are aggregates and are dropped. The Africa (Ember) total is kept separately in clean/africa_ember.parquet for checks.
- Years: 2000 to 2024. 2025 dropped: only 7 countries report it.
- Columns: 19 kept, renamed with the unit in the name (energy_columns.py). Units from the codebook: TWh, kWh per person, %, people.
- Sources: every electricity column names Ember; most also name the Energy Institute. Population comes from OWID's population sources.
- Unit checks: TWh x 1e9 / population matches kWh per person; the nine sources add up to the total; the renewables share matches. Largest gaps are rounding (0.001).
- Zeros: Lesotho shows 0 TWh in 2023 and 2024 after 0.48 TWh in 2022. Treated as missing.
- Coverage: kept countries with generation in at least 20 of 25 years. Dropped Western Sahara (10 years) and South Sudan (13 years, rows start in 2012).
- Data ends in 2023 for Central African Republic, Comoros, Reunion, Saint Helena, and Sao Tome and Principe.
- Result: clean/energy.parquet, 55 countries, 1370 rows, 19 columns. Rebuild with: uv run clean.py
MD
tail -n 15 notes.mdReunion and Saint Helena are territories, not independent states, but they are in M49 Africa and have their own electricity systems, so they stay. If your question were about countries in the African Union, you would remove them and write that down too.
Check it worked
tail shows the new section, ending with the line about clean/energy.parquet. Your project now has raw/ (untouched), clean/ with two Parquet files, the scripts, and a notes.md that explains every row and column you removed.
Next steps
- Give each country its subregion, Northern, Western, Eastern, Middle or Southern Africa, in part 3: add African subregions with a checked join.
- Think harder about the gaps you found, and when to fill them, in handle missing data without distorting results.
- For files with messy text, stray spaces and mixed date formats, see clean a CSV file with pandas.
- Look back at the first questions you wrote down in part 1 and tick off the ones this part answered.
Part of these paths
Related tutorials
- Download a public energy dataset and get to know it before analysingYou will download the Our World in Data energy dataset at a pinned commit, prove it is the exact file with a SHA-256 check, read its codebook, answer the first questions about its rows, regions and gaps with pandas, and end with a notes.md of what to answer next.
- Handle missing data without distorting your resultsYou will measure where a survey's gaps are, compare dropping rows, mean, median, group-wise and time-series fills by how far each moves the averages, add missing-value flags and write down the choice you made.
- How to Clean and Summarise a CSV File with pandasYou will take a messy orders CSV with stray spaces, mixed spellings, money written as text, odd dates, missing values and a duplicate row, and clean it with pandas 3.1 on Python 3.15 into a tidy file plus per-country and per-month summaries.
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