Skip to main content

Data analysis · Intermediate · 15 min

Add African subregions to the energy data with a checked join

By Padding · Updated 18 Nov 2026
Python 3.15.2 · pandas 3.1.1 · pyarrow 26.0.1 · uv 0.13 (checked on python:3.15-slim)

You will build a UN M49 subregion lookup for Africa keyed by ISO code, join it to the cleaned energy data with pandas checks that fail loudly, explain every code that did not match, and save a table with a subregion on every row.

On this page

The energy data from part 2 knows each country's name, ISO code and electricity figures, but nothing about where the country sits. To compare West Africa with Southern Africa you need a region on every row, and that comes from a second table joined on a shared key.

A join is where analyses quietly go wrong. A duplicate in the lookup copies rows, so totals grow. A key that does not match leaves a row without a region, and it drops out of every regional sum without a word. Part 2 already kept only African M49 codes, so every row should find a region. This part does not assume that: it joins with two pandas checks switched on, proves no row was left without a subregion, and accounts for every lookup entry that found no data, so you can say exactly what is in each region and what is not.

The regions come from the UN Statistics Division's M49 standard, which most international statistics use. It splits Africa into five groups: Northern Africa, plus Eastern, Middle, Southern and Western Africa. The UN says the groupings exist for statistical convenience and say nothing about political affiliation. Note that too, because readers of your results may use a different grouping and place some countries elsewhere.

You will keep working in ~/energy-demo. For the general pitfalls of joins outside this dataset, see join DataFrames in pandas without losing rows. If you know SQL, merge(how="left") is a LEFT JOIN, and the checks below are worth adding to SQL joins too.

Step 1 · Check what part 2 left you

Start by confirming both raw files are unchanged and the clean file is what part 2 wrote:

Bash
cd ~/energy-demo
uv run check_raw.py
cat > inspect_clean.py <<'PY'
import pandas as pd

energy = pd.read_parquet("clean/energy.parquet")
print("rows:", len(energy))
print("countries:", energy["iso_code"].nunique())
print("years:", energy["year"].min(), "to", energy["year"].max())
print("repeated code-and-year pairs:", int(energy.duplicated(["iso_code", "year"]).sum()))
print("columns:", ", ".join(energy.columns))
PY
uv run inspect_clean.py

The join only needs iso_code. The other 18 columns ride along unchanged, so every measurement you kept in part 2, including generation_twh, renewables_twh and generation_kwh_per_person, reaches the regional table.

Check it worked

check_raw.py prints OK next to both file names, the data file and the codebook. The script prints rows: 1370, countries: 55, years: 2000 to 2024 and repeated code-and-year pairs: 0, followed by the 19 column names from energy_columns.py, from country to renewables_share_pct. These are the numbers part 2's clean.py reported. If yours differ, re-run uv run clean.py from part 2 before you go on. A repeated pair would mean part 2 left duplicate rows, which its assert should have stopped.

Step 2 · Write the subregion lookup

The lookup has one row per African country or area in M49: its ISO 3166 alpha-3 code, its M49 name and its subregion. The values below are copied from the UN's M49 overview table. In M49's own structure, Northern Africa is a sub-region, while the other four are "intermediate regions" inside the sub-region Sub-Saharan Africa. The lookup flattens that into one subregion column with five values, which is what the series compares.

Keep the lookup in its own lookups/ folder, apart from data you download or generate, so it is clear it was typed by hand:

Bash
cd ~/energy-demo
mkdir -p lookups
cat > lookups/m49_africa.csv <<'CSV'
iso3,m49_name,subregion
DZA,Algeria,Northern Africa
EGY,Egypt,Northern Africa
LBY,Libya,Northern Africa
MAR,Morocco,Northern Africa
SDN,Sudan,Northern Africa
TUN,Tunisia,Northern Africa
ESH,Western Sahara,Northern Africa
IOT,British Indian Ocean Territory,Eastern Africa
BDI,Burundi,Eastern Africa
COM,Comoros,Eastern Africa
DJI,Djibouti,Eastern Africa
ERI,Eritrea,Eastern Africa
ETH,Ethiopia,Eastern Africa
ATF,French Southern Territories,Eastern Africa
KEN,Kenya,Eastern Africa
MDG,Madagascar,Eastern Africa
MWI,Malawi,Eastern Africa
MUS,Mauritius,Eastern Africa
MYT,Mayotte,Eastern Africa
MOZ,Mozambique,Eastern Africa
REU,Réunion,Eastern Africa
RWA,Rwanda,Eastern Africa
SYC,Seychelles,Eastern Africa
SOM,Somalia,Eastern Africa
SSD,South Sudan,Eastern Africa
UGA,Uganda,Eastern Africa
TZA,United Republic of Tanzania,Eastern Africa
ZMB,Zambia,Eastern Africa
ZWE,Zimbabwe,Eastern Africa
AGO,Angola,Middle Africa
CMR,Cameroon,Middle Africa
CAF,Central African Republic,Middle Africa
TCD,Chad,Middle Africa
COG,Congo,Middle Africa
COD,Democratic Republic of the Congo,Middle Africa
GNQ,Equatorial Guinea,Middle Africa
GAB,Gabon,Middle Africa
STP,Sao Tome and Principe,Middle Africa
BWA,Botswana,Southern Africa
SWZ,Eswatini,Southern Africa
LSO,Lesotho,Southern Africa
NAM,Namibia,Southern Africa
ZAF,South Africa,Southern Africa
BEN,Benin,Western Africa
BFA,Burkina Faso,Western Africa
CPV,Cabo Verde,Western Africa
CIV,Côte d’Ivoire,Western Africa
GMB,Gambia,Western Africa
GHA,Ghana,Western Africa
GIN,Guinea,Western Africa
GNB,Guinea-Bissau,Western Africa
LBR,Liberia,Western Africa
MLI,Mali,Western Africa
MRT,Mauritania,Western Africa
NER,Niger,Western Africa
NGA,Nigeria,Western Africa
SHN,Saint Helena,Western Africa
SEN,Senegal,Western Africa
SLE,Sierra Leone,Western Africa
TGO,Togo,Western Africa
CSV

A table typed by hand needs its own test before you trust it. Check the size, that no code appears twice, that every code has the ISO shape, and how many places each subregion holds:

Bash
cd ~/energy-demo
cat > check_lookup.py <<'PY'
import pandas as pd

lookup = pd.read_csv("lookups/m49_africa.csv")
print("rows:", len(lookup))
print("distinct codes:", lookup["iso3"].nunique())
bad = ~lookup["iso3"].str.fullmatch(r"[A-Z]{3}")
print("codes that are not three capital letters:", int(bad.sum()))
print()
print(lookup["subregion"].value_counts().sort_index().to_string())
PY
uv run check_lookup.py

Check it worked

The script prints rows: 60, distinct codes: 60 and codes that are not three capital letters: 0, then the counts: Eastern Africa 22, Middle Africa 9, Northern Africa 7, Southern Africa 5 and Western Africa 17. Those match the M49 table. If distinct codes is lower than rows, a code is listed twice; find it with lookup[lookup["iso3"].duplicated(keep=False)] before you go on.

Step 3 · See why the key is the code, not the name

Both tables have a name column, so it is tempting to join on it. Compare the names for the codes the two tables share:

Bash
cd ~/energy-demo
cat > names.py <<'PY'
import pandas as pd

energy = pd.read_parquet("clean/energy.parquet")
lookup = pd.read_csv("lookups/m49_africa.csv")

owid = energy.drop_duplicates("iso_code").set_index("iso_code")["country"]
both = lookup.set_index("iso3").join(owid, how="inner")
differ = both[both["m49_name"] != both["country"]]
print("codes in both files:", len(both))
print("same code, different name:", len(differ))
print(differ[["m49_name", "country"]].to_string())
PY
uv run names.py

Five countries are spelled differently: an accent (Réunion), a curly apostrophe (Côte d’Ivoire), an official long form (United Republic of Tanzania), a missing word (Democratic Republic of the Congo) and a renamed country (Cabo Verde, formerly Cape Verde). A name join would silently drop all five. African country names have official forms in English, French, Portuguese and Arabic, and every source picks its own spelling, so names are a poor key across sources. ISO codes are designed for exactly this.

Check it worked

The script prints codes in both files: 55 and same code, different name: 5, then a table with the five pairs above. The table shows the same countries with different spellings, and each pair has the same code.

Step 4 · Join with validate and indicator

Now join. Rename the lookup's iso3 column to iso_code so both sides use the same key name, and switch on two arguments:

  • validate="m:1" says many data rows may share one lookup row, but each code may appear in the lookup only once. If that is not true, pandas raises an error instead of copying rows.
  • indicator=True adds a _merge column saying, for each row, whether the code was found in both tables (both) or only in the data (left_only).
Bash
cd ~/energy-demo
cat > join.py <<'PY'
import pandas as pd

energy = pd.read_parquet("clean/energy.parquet")
lookup = pd.read_csv("lookups/m49_africa.csv").rename(columns={"iso3": "iso_code"})

joined = energy.merge(
    lookup,
    on="iso_code",
    how="left",
    validate="m:1",
    indicator=True,
)

print("rows before:", len(energy))
print("rows after: ", len(joined))
print()
print(joined["_merge"].value_counts().to_string())

assert len(joined) == len(energy), "the join added or lost rows"
joined.to_parquet("clean/energy_joined.parquet", index=False)
PY
uv run join.py

how="left" keeps every data row whether or not it finds a region, which is what lets you count the misses. With an inner join, a row whose code was missing from the lookup would vanish and you would never see the count. The assert stops the script before it saves anything if the row count changed.

To see what validate protects you from, break the lookup on purpose in memory. This script adds Nigeria a second time, in the wrong subregion, then joins with and without the check:

Bash
cd ~/energy-demo
cat > validate_demo.py <<'PY'
import pandas as pd

energy = pd.read_parquet("clean/energy.parquet")
lookup = pd.read_csv("lookups/m49_africa.csv").rename(columns={"iso3": "iso_code"})

# A copy-paste slip: Nigeria listed twice, once in the wrong subregion
slip = pd.DataFrame([{"iso_code": "NGA", "m49_name": "Nigeria", "subregion": "Middle Africa"}])
broken = pd.concat([lookup, slip])

loose = energy.merge(broken, on="iso_code", how="left")
print("without validate:", len(energy), "rows became", len(loose))

try:
    energy.merge(broken, on="iso_code", how="left", validate="m:1")
except pd.errors.MergeError as err:
    print("with validate:", str(err).splitlines()[0])
PY
uv run validate_demo.py

Without the check, all 25 Nigerian rows are copied, one copy per subregion. Nigeria's electricity would then be counted in Western and Middle Africa, and no error would appear anywhere. The file on disk is untouched; the slip exists only inside the script.

Check it worked

join.py prints rows before: 1370 and rows after: 1370, then both 1370, left_only 0 and right_only 0. Every row of the clean file found a subregion. right_only is always 0 in a left join, because rows that exist only in the lookup are not kept; the next step checks that side separately. validate_demo.py prints without validate: 1370 rows became 1395, then with validate: Merge keys are not unique in right dataset; not a many-to-one merge.

Step 5 · Account for every code that did not match

A join can miss on either side, and each side needs its own check:

  1. Data rows with no subregion. Part 2 kept only codes from africa_m49_codes.txt, and the lookup holds the same 60 codes, so this must be 0. If it is not, the two hand-typed lists disagree and one of them has a typo. Make the script stop rather than carry on.
  2. Lookup codes with no data. M49 lists 60 entries and the clean file has 55 countries. For each missing one, find out whether OWID never had it, or whether it was in the raw file and part 2 removed it.
Bash
cd ~/energy-demo
cat > unmatched.py <<'PY'
import pandas as pd

joined = pd.read_parquet("clean/energy_joined.parquet")
lookup = pd.read_csv("lookups/m49_africa.csv")
raw = pd.read_csv("raw/owid-energy-data.csv", usecols=["iso_code"])
raw_codes = set(raw["iso_code"].dropna())

# 1. Data rows with no subregion. Part 2 kept only African codes, so there should be none.
left_only = joined[joined["_merge"] == "left_only"]
print("countries with no subregion:", left_only["iso_code"].nunique())
if not left_only.empty:
    print(left_only[["country", "iso_code"]].drop_duplicates().to_string(index=False))
    raise SystemExit("fix the code in lookups/m49_africa.csv or africa_m49_codes.txt")

# 2. Lookup codes that found no data rows, and why.
matched = set(joined.loc[joined["_merge"] == "both", "iso_code"])
print()
print("lookup codes with no data:")
for row in lookup[~lookup["iso3"].isin(matched)].itertuples():
    reason = "removed before clean/" if row.iso3 in raw_codes else "not in the OWID file"
    print(f"  {row.iso3}  {row.m49_name}: {reason}")
PY
uv run unmatched.py

The five misses are all on the lookup side, and they have two different causes. British Indian Ocean Territory, French Southern Territories and Mayotte are not in the OWID file at all: small territories with no separate electricity figures in this dataset. Western Sahara and South Sudan are in the raw file, but part 2 removed them because they had generation figures for only 10 and 13 of the 25 years. The first group is a gap in the source; the second is your own decision, and notes.md already says why. Write both down here too, so a reader who counts M49's 60 entries knows why you have 55.

The two checks also guard each other. Suppose you had typed NGR instead of NGA for Nigeria in the lookup. Nigeria's 25 rows would come out as left_only, the script would stop and print Nigeria NGA, and NGR would show up as a lookup code not in the OWID file. A typo cannot hide on one side without showing on the other.

Check it worked

The script prints countries with no subregion: 0, then five lookup codes with no data, in the lookup's order: ESH (removed before clean/), IOT, ATF and MYT (not in the OWID file) and SSD (removed before clean/). If the first number is above 0, the script lists the country and code that found no subregion and stops; correct that code in whichever list has it wrong, then run join.py again. If a code other than ESH or SSD says removed before clean/, your part 2 kept fewer countries than expected: re-run part 2's clean.py and check its dropped for coverage line.

Step 6 · Save the table with subregions

Keep the rows that matched, drop the helper columns, put the identifying columns first and save as clean/energy_regions.parquet, the country-level table with a subregion on every row. Then read the file back and test it, because a check on the file you wrote is stronger than a check on the DataFrame you meant to write:

Bash
cd ~/energy-demo
cat > save_regions.py <<'PY'
import pandas as pd

joined = pd.read_parquet("clean/energy_joined.parquet")

regions = (
    joined[joined["_merge"] == "both"]
    .drop(columns=["_merge", "m49_name"])
    .sort_values(["subregion", "country", "year"])
    .reset_index(drop=True)
)
first = ["country", "iso_code", "subregion", "year"]
regions = regions[first + [c for c in regions.columns if c not in first]]
regions.to_parquet("clean/energy_regions.parquet", index=False)

check = pd.read_parquet("clean/energy_regions.parquet")
assert check["subregion"].notna().all(), "a row has no subregion"
assert not check.duplicated(["iso_code", "year"]).any(), "a country-year appears twice"
print("rows:", len(check))
print("countries:", check["iso_code"].nunique())
print("columns:", len(check.columns))
print()
print(check.groupby("subregion")["iso_code"].nunique().to_string())
PY
uv run save_regions.py
ls clean

The table keeps OWID's spelling in country, which is what the source you credit uses. It has part 2's 19 columns plus subregion. Keep clean/energy_joined.parquet for now: it is the record of what matched, and the last part of the series tidies up.

Check it worked

The script prints rows: 1370, countries: 55 and columns: 20, then the countries per subregion: Eastern Africa 18, Middle Africa 9, Northern Africa 6, Southern Africa 5 and Western Africa 17. Eastern Africa has 18 rather than M49's 22 because of the three territories OWID does not cover and South Sudan; Northern Africa has 6 rather than 7 because of Western Sahara. ls clean lists africa_ember.parquet, energy.parquet, energy_joined.parquet and energy_regions.parquet.

Step 7 · Save a second table for regional totals

clean/energy_regions.parquet is the table for comparing countries: part 2 removed the countries with too few years and stopped at 2024. Regional totals have a different job. Part 4 adds up each subregion and checks the sum against the dataset's own Africa (Ember) total, and that total counts every African country in every year, South Sudan and Western Sahara included, up to 2025. A sum built from fewer countries would miss it for reasons that have nothing to do with your code.

So join the same lookup, with the same two checks, to every African country row from 2000 in the raw file, and save it as clean/energy_africa.parquet. Parts 4, 5 and 7 build their regional figures from this table, and part 4 decides for itself where the regional series has to stop:

Bash
cd ~/energy-demo
cat > save_africa.py <<'PY'
from pathlib import Path

import pandas as pd

from energy_columns import COLUMNS

codes = Path("africa_m49_codes.txt").read_text().split()
lookup = pd.read_csv("lookups/m49_africa.csv").rename(columns={"iso3": "iso_code"})
raw = pd.read_csv("raw/owid-energy-data.csv", usecols=list(COLUMNS))
raw = raw[list(COLUMNS)].rename(columns=COLUMNS)

# Every African country row from 2000: no coverage drops, no year cut-off, zeros as published.
rows = raw[raw["iso_code"].isin(codes) & (raw["year"] >= 2000)]
africa = rows.merge(lookup, on="iso_code", how="left", validate="m:1", indicator=True)
assert len(africa) == len(rows), "the join added or lost rows"
assert (africa["_merge"] == "both").all(), "a row found no subregion"

africa = africa.drop(columns=["_merge", "m49_name"]).sort_values(["subregion", "country", "year"])
first = ["country", "iso_code", "subregion", "year"]
africa = africa[first + [c for c in africa.columns if c not in first]].reset_index(drop=True)
africa.to_parquet("clean/energy_africa.parquet", index=False)

print("rows:", len(africa))
print("countries:", africa["iso_code"].nunique())
print("years:", africa["year"].min(), "to", africa["year"].max())
print()
print(africa.groupby("subregion")["iso_code"].nunique().to_string())
PY
uv run save_africa.py
ls clean

Check it worked

The script prints rows: 1414, countries: 57 and years: 2000 to 2025, then Eastern Africa 19, Middle Africa 9, Northern Africa 7, Southern Africa 5 and Western Africa 17: South Sudan and Western Sahara are back, and only the three territories OWID does not cover are missing. ls clean now lists five files, with energy_africa.parquet added. Lesotho's zeros for 2023 and 2024 are still in this table as published; part 7 measures what they are worth.

Step 8 · Record the join decisions

Add what you did and what you found to notes.md, below the sections from parts 1 and 2, so part 4 can rely on it without re-running anything:

Bash
cd ~/energy-demo
cat >> notes.md <<'MD'

## Regions (part 3)

- Lookup: lookups/m49_africa.csv, 60 African entries from the UN M49 overview table
  (unstats.un.org/unsd/methodology/m49/overview/), copied 26 Nov 2026. Five subregions:
  Northern Africa (an M49 sub-region) and Eastern, Middle, Southern and Western Africa
  (M49 intermediate regions in Sub-Saharan Africa). Groupings are statistical, not political.
- Joined on ISO alpha-3 code with merge(how="left", validate="m:1", indicator=True).
  Row count unchanged; every row found a subregion (left_only 0). Names are not a safe key:
  5 African countries are spelled differently.
- 55 African countries matched, 1,370 rows, saved as clean/energy_regions.parquet
  (part 2's 19 columns plus subregion). Per subregion: Eastern 18, Middle 9, Northern 6,
  Southern 5, Western 17.
- For regional totals: clean/energy_africa.parquet, the same join on every African country row from
  2000 (57 countries, 1,414 rows, 2000 to 2025, no coverage drops, zeros as published), so sums can be
  checked against the Africa (Ember) total in part 4.
- Lookup codes with no data: British Indian Ocean Territory, French Southern Territories and
  Mayotte are not in the OWID file; South Sudan and Western Sahara were removed in part 2 for coverage.
- Territories in the table: Réunion and Saint Helena, kept in part 2 because they are in M49 Africa
  and have their own electricity systems. Both have data only to 2023.
MD
grep -c "^## " notes.md

Check it worked

grep prints 7: five section headings from part 1, one from part 2 and the new one. Open notes.md and check the new Regions (part 3) section sits below the part 1 sections and Cleaning decisions (part 2), and that its numbers match what join.py, unmatched.py, save_regions.py and save_africa.py printed. If you run this step twice, the section appears twice and the count is 8; delete the copy by hand.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.