Data analysis · Intermediate · 18 min
Summarise electricity by region and decade with group-by
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 turn the country-level energy table into regional totals by year, per-person figures computed from those totals, a subregion by decade table and a ranking of countries within each subregion, all checked against the dataset's own Africa total.
On this page
Part 3 gave every African country in the energy table a UN M49 subregion. Now you can ask regional questions: how much electricity did Western Africa generate per person in 2024, how did the 2000s compare with the 2010s, and which country leads each subregion?
Group-by answers these in a few lines, and it is also where many analyses go quietly wrong. The usual mistake is to average the countries' own per-person figures, which gives Seychelles (about 130,000 people) the same weight as Ethiopia (more than 130 million). This part builds every regional figure from totals instead, then checks those totals against the Africa figure that Ember publishes in the same file. If your sums and Ember's disagree, the code or the coverage has a problem, and you want to know before you draw a chart.
You keep working in ~/energy-demo. Everything this part writes goes into a new summary/ folder, and part 5 reads from it.
Step 1 · Confirm the joined table is what part 3 left
Start every part the same way: check the raw file has not changed, then look at the table you are about to summarise. A summary of the wrong input is worse than no summary, because it looks finished.
cd ~/energy-demo
uv run check_raw.py
cat > inspect_joined.py <<'PY'
import pandas as pd
df = pd.read_parquet("clean/energy_africa.parquet")
print("rows:", len(df), "countries:", df["country"].nunique())
print("years:", df["year"].min(), "to", df["year"].max())
print("missing subregion:", int(df["subregion"].isna().sum()))
print("repeated country-years:", int(df.duplicated(["iso_code", "year"]).sum()))
print()
print(df.groupby("subregion")["country"].nunique().to_string())
PY
uv run inspect_joined.pyThe "repeated country-years" line matters more than it looks. If any country appeared twice in one year, for example after a join that matched a code to two subregions, every sum below would count it twice.
Check it worked
check_raw.py prints OK for both files. The script then prints rows: 1414 countries: 57, years: 2000 to 2025, missing subregion: 0 and repeated country-years: 0, followed by the number of countries per subregion: Eastern Africa 19, Middle Africa 9, Northern Africa 7, Southern Africa 5 and Western Africa 17. This is the table part 3 saved for regional totals, so it still has South Sudan, Western Sahara and 2025, which part 2's country table drops. If you changed the lookup in part 3 (dropping a territory, say), your counts will differ slightly. That is fine, as long as missing subregion and repeated country-years are both 0.
Step 2 · Add up generation and population by subregion and year
Group by two keys, subregion and year, and add up the quantities that can be added: terawatt-hours (TWh) and people. A per-person figure cannot be added, so leave generation_kwh_per_person out of this step.
A per-person figure for a region also needs generation and population from the same set of countries. If a country has a population but no generation for some year, its people would lower the average without any electricity to go with them. So keep only rows that have both before you sum. Named aggregation gives each output column a clear name, and counting countries per group shows you when coverage changes:
cd ~/energy-demo
cat > region_year.py <<'PY'
from pathlib import Path
import pandas as pd
df = pd.read_parquet("clean/energy_africa.parquet")
# Per-person figures need both numbers, so keep a row only when it has both.
both = df["generation_twh"].notna() & df["population"].notna()
print("rows without both generation and population:", int((~both).sum()))
df = df[both]
sums = (
df.groupby(["subregion", "year"], as_index=False)
.agg(
countries=("iso_code", "nunique"),
population=("population", "sum"),
generation_twh=("generation_twh", "sum"),
renewables_twh=("renewables_twh", "sum"),
)
)
Path("summary").mkdir(exist_ok=True)
sums.to_parquet("summary/region_year_sums.parquet", index=False)
print("rows:", len(sums))
view = sums[sums["year"] == 2023].assign(population_m=sums["population"] / 1e6)
print(view.drop(columns="population").round(1).to_string(index=False))
PY
uv run region_year.pyThe 14 rows left out are all Western Sahara from 2010 to 2023: the dataset gives its population for those years but no generation.
Lesotho is the opposite case. Its 2023 and 2024 rows pass the filter with a published total of exactly 0 TWh, which part 2 judged to be a gap rather than a fact. This table keeps them as published, as part 3 did, so Lesotho's 2.3 million people count in Southern Africa with no electricity. Part 7 measures what that is worth: treating the zeros as gaps raises Southern Africa's 2024 figure by about 3 per cent.
Check it worked
The script prints rows without both generation and population: 14 and rows: 129, then one line per subregion for 2023. Northern Africa shows 6 countries, 429.8 TWh, of which 48.7 TWh renewable, for 268.0 million people. Western Africa shows 17 countries and 102.8 TWh for 445.0 million people. summary/region_year_sums.parquet now exists.
Step 3 · Check your totals against the Africa (Ember) row
The dataset holds an aggregate row, Africa (Ember), which part 2 kept out of your country table and saved on its own as clean/africa_ember.parquet. It is a total of country figures, so adding your five subregions back together should land on it or very close. This is the cheapest test you will ever run on a summary: it catches double counting, a lost subregion, a wrong unit and missing countries in one go.
Part 2 saved that file for this check, but it stops at 2024, because part 2 limited every table to 2000 to 2024. Your joined table still runs to 2025, and 2025 is the year this check most needs to test, so read the aggregate from the raw file instead. For 2000 to 2024 the values are the same as in clean/africa_ember.parquet:
cd ~/energy-demo
cat > check_africa.py <<'PY'
import pandas as pd
sums = pd.read_parquet("summary/region_year_sums.parquet")
ours = sums.groupby("year").agg(
countries=("countries", "sum"),
ours_twh=("generation_twh", "sum"),
)
raw = pd.read_csv("raw/owid-energy-data.csv")
ember = (
raw.loc[raw["country"] == "Africa (Ember)", ["year", "electricity_generation"]]
.rename(columns={"electricity_generation": "ember_twh"})
.set_index("year")
)
check = ours.join(ember, how="outer")
check["gap_pct"] = (check["ours_twh"] / check["ember_twh"] - 1) * 100
print(check.round(2).to_string())
worst = check.loc[:2023, "gap_pct"].abs().max()
print()
print(f"largest gap 2000 to 2023: {worst:.3f}%")
PY
uv run check_africa.pyRead the table from the bottom up:
- 2025: only 7 countries have data, and your total is 35 per cent short. Ember's own row includes estimates for the rest. A regional 2025 figure built from countries would show a collapse that never happened.
- 2024: 51 countries, 0.37 per cent short. Six small places have no 2024 figures yet (Central African Republic, Comoros, Reunion, Saint Helena, Sao Tome and Principe, Western Sahara). The gap is small enough to keep 2024, with a note.
- 2010 to 2023: about 0.09 TWh short each year. That is the size of Western Sahara's last reported value, which suggests Ember's total still carries an estimate for it after the country rows stop.
- 2000 to 2009: an exact match.
So this analysis stops at 2024. If the check had shown a gap of 10 per cent in 2012, you would go looking for a dropped subregion or a country counted twice before going any further.
Check it worked
The first line of the table reads 2000 56 441.07 441.07 0.00. The 2024 line shows a gap of -0.37 and the 2025 line -35.46. The last line reads largest gap 2000 to 2023: 0.013%.
Step 4 · Compute per-person figures from the totals
Divide total generation by total population for each subregion and year. TWh to kWh is a factor of 10⁹. The renewables share works the same way: total renewable TWh over total TWh, not an average of the countries' shares.
The script also computes the tempting shortcut, the plain mean of each country's own generation_kwh_per_person, so you can see how far apart the two are:
cd ~/energy-demo
cat > per_person.py <<'PY'
import pandas as pd
LAST_YEAR = 2024 # 2025 covers only 7 countries; see the Africa (Ember) check
sums = pd.read_parquet("summary/region_year_sums.parquet")
sums = sums[sums["year"] <= LAST_YEAR].copy()
# Ratios of sums: TWh to kWh is 1e9, then divide by people.
sums["kwh_per_person"] = sums["generation_twh"] * 1e9 / sums["population"]
sums["renewables_share_pct"] = sums["renewables_twh"] / sums["generation_twh"] * 100
sums.to_parquet("summary/region_year.parquet", index=False)
# The tempting shortcut: average the countries' own per-person values.
df = pd.read_parquet("clean/energy_africa.parquet")
naive = (
df[df["year"] == LAST_YEAR]
.groupby("subregion")["generation_kwh_per_person"]
.mean()
.rename("mean_of_countries")
)
compare = (
sums[sums["year"] == LAST_YEAR]
.set_index("subregion")[["kwh_per_person"]]
.rename(columns={"kwh_per_person": "from_sums"})
.join(naive)
)
print(f"kWh per person, {LAST_YEAR}")
print(compare.round().astype("int64").to_string())
PY
uv run per_person.pyThe two columns answer different questions. from_sums is the electricity per resident of the subregion: it is what you get if you pool everyone. mean_of_countries is the typical country, with every country counted once whatever its size.
In Southern Africa the pooled figure (3,462 kWh) is almost three times the country mean (1,252 kWh), because South Africa has about 64 million of the region's 73 million people and generates far more per person than its four neighbours. Lesotho's published zero for 2024 also pulls the country mean down. In Eastern Africa it goes the other way: Seychelles and Mauritius, two small island states with high per-person generation, pull the country mean up to 643 kWh, while the pooled figure for the region's 500 million or so people is 230 kWh. Neither number is wrong, but only the pooled one can be compared with the Africa (Ember) total, so use it for regional trends and name it clearly when you report it.
Check it worked
The table prints five lines. Southern Africa reads 3462 1252, Eastern Africa 230 643 and Western Africa 217 258. summary/region_year.parquet now holds 125 rows: five subregions for each year from 2000 to 2024.
Step 5 · Summarise each subregion by decade
Add a decade column with integer division, year // 10 * 10, so 2007 becomes 2000. Then build a subregion by decade table with pivot_table, summing generation and population within each cell and dividing afterwards. That keeps the ratio-of-sums rule from the last step: each cell is the decade's total generation over its total person-years, so the result is the average kWh per person per year for that decade.
cd ~/energy-demo
cat > decades.py <<'PY'
import pandas as pd
ry = pd.read_parquet("summary/region_year.parquet")
ry["decade"] = ry["year"] // 10 * 10
totals = ry.pivot_table(
index="subregion",
columns="decade",
values=["generation_twh", "population"],
aggfunc="sum",
)
per_person = totals["generation_twh"] * 1e9 / totals["population"]
per_person.columns = [f"{d}s" for d in per_person.columns]
years = ry.groupby("decade")["year"].agg(["min", "max"])
print("years in each decade:")
print(years.to_string())
print()
print("average kWh per person per year")
print(per_person.round().astype("int64").to_string())
per_person.round(1).to_csv("summary/region_decade.csv")
PY
uv run decades.pyThe script prints the years in each decade first, on purpose: the 2020s hold five years, not ten. Because each cell is an average per year, the 2020s column is still comparable with the others, but any total for the decade would not be. Write "2020 to 2024" rather than "the 2020s" when you report it.
Four subregions rise from decade to decade. Southern Africa falls, from 4,321 to 3,463 kWh per person. Part 5 measures that change properly, and part 7 asks how much of it comes from population growth rather than lower generation.
Check it worked
The first table ends with 2020 2020 2024. In the second, Southern Africa reads 4321 4085 3463 and Middle Africa 143 201 245. The first line of summary/region_decade.csv is subregion,2000s,2010s,2020s.
Step 6 · Rank countries within each subregion
A rank within a group needs groupby(...).rank(), not a sort of the whole table. method="min" gives tied countries the same rank, as in a sports table. The script also adds how many countries each rank is out of, since first of 5 and first of 17 mean different things:
cd ~/energy-demo
cat > rank.py <<'PY'
import pandas as pd
YEAR = 2024
df = pd.read_parquet("clean/energy_africa.parquet")
latest = df[(df["year"] == YEAR) & df["generation_kwh_per_person"].notna()].copy()
latest["rank_in_region"] = (
latest.groupby("subregion")["generation_kwh_per_person"]
.rank(method="min", ascending=False)
.astype(int)
)
latest["countries_in_region"] = latest.groupby("subregion")["iso_code"].transform("size")
latest["kwh_per_person"] = latest["generation_kwh_per_person"].round().astype("int64")
table = latest.sort_values(["subregion", "rank_in_region"])[
["subregion", "rank_in_region", "countries_in_region", "country", "kwh_per_person"]
]
table.to_csv("summary/country_rank_2024.csv", index=False)
top = table[table["rank_in_region"] == 1]
print(f"highest kWh per person in each subregion, {YEAR}")
print(top.to_string(index=False))
print()
print("Western Africa, all ranks")
print(table[table["subregion"] == "Western Africa"].to_string(index=False))
PY
uv run rank.pyPer-person rankings favour small countries with one large power plant or a tourist economy. Seychelles and Cape Verde top their subregions, while Nigeria, with more people than the other fifteen Western African countries in this table put together, is ninth of 16 at 161 kWh per person. Keep both views: the pooled regional figure from earlier says where most people are, and the rank says how each country compares with its neighbours.
Check it worked
The first table lists one country per subregion: Seychelles (4830) in Eastern Africa, Gabon (1024) in Middle Africa, Libya (4686) in Northern Africa, South Africa (3867) in Southern Africa and Cape Verde (991) in Western Africa. In the Western Africa list, Ghana is second at 705 and Nigeria ninth at 161. summary/country_rank_2024.csv has 52 lines: a header and the 51 countries with 2024 data.
Step 7 · Record the decisions in notes.md
Add what you decided and why to the notes from part 1, so part 5 starts from the same facts. >> appends, so earlier notes stay as they are:
cd ~/energy-demo
grep -c "^- " notes.md
cat >> notes.md <<'MD'
## Part 4: regional summaries
- Regional figures are ratios of sums: total TWh over total population, total renewable TWh over
total TWh. Never the mean of country per-person values (2024 Southern Africa: 3,462 kWh pooled
against 1,252 for the country mean).
- Rows need both generation and population to count. Excluded: Western Sahara 2010 to 2023 (14 rows).
Lesotho's published zeros for 2023 and 2024 are counted; part 7 tests them.
- Check against Africa (Ember): exact 2000 to 2009, within 0.02% to 2023, 0.37% short in 2024
(six small places missing), 35% short in 2025 (7 countries). The study stops at 2024.
- Decades are averages per year; "2020s" means 2020 to 2024 only.
- Outputs: summary/region_year.parquet, summary/region_decade.csv, summary/country_rank_2024.csv.
MD
ls summary
grep -c "^- " notes.md
grep -c "^## Part 4" notes.mdCheck it worked
ls summary lists four files: country_rank_2024.csv, region_decade.csv, region_year.parquet and region_year_sums.parquet. The two grep -c "^- " counts, printed before and after the append, differ by 5, and grep -c "^## Part 4" notes.md prints 1. If it prints 2, you ran the command twice; delete the repeated section by hand. Open notes.md and check that each figure in the new section matches what your scripts printed.
Next steps
- Turn the regional series into growth rates, indexes and percentage-point changes: measure change over time in the energy data, part 5 of this series.
- Go back over the join that this part relies on: add African subregions to the energy data with a checked join.
- For more on named aggregation, transform and filter on groups: group and aggregate data in pandas.
- For moving between long and wide tables like the decade pivot: reshape data with pivot and melt.
Part of these paths
Related tutorials
- Add African subregions to the energy data with a checked joinYou 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.
- Group and aggregate data in pandasYou will summarise a shop's sales by region, month and city with pandas groupby, named aggregation, transform and filter, and finish with a regional report whose totals you have checked against the raw data.
- Reshape data between wide and long with pivot and meltYou will turn a one-column-per-month spreadsheet export into long, tidy rows with pandas 3.1 and back again, handle duplicate entries with pivot_table, compute shares with crosstab and move between shapes with stack and unstack.
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