Skip to main content

Data analysis · Intermediate · 20 min

Measure growth over time in the energy data

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 measure how electricity per person has changed in each African subregion since 2000 with year-on-year change, compound annual growth, an index with 2000 as 100, a three-year rolling mean and percentage-point changes in the renewables share, then rank countries by growth and test whether the start year changes that ranking.

On this page

Part 4 left you with one row per African subregion and year: total generation, total population and electricity per person built from those totals. A table of levels tells you where each subregion stands. It does not say how fast things are moving, whether 2024 was a good year or a bad one, or whether a renewables share that "rose by 600 per cent" means much at all.

This part turns the levels into measures of change. Each measure answers a different question, and each has a trap:

  • Year-on-year change: how did this year compare with the last? Trap: comparing across the boundary between two subregions.
  • Compound annual growth rate (CAGR): what steady yearly rate gets you from the first year to the last? Trap: counting years instead of steps between them.
  • Index with 2000 = 100: how do series with very different sizes compare? Trap: forgetting that per person is generation divided by population, so both move.
  • Rolling mean: what is the trend under the noise? Trap: a centred window has no value for the latest year.
  • Percentage points: how did a share change? Trap: a percentage change of a percentage.

Then you rank countries by growth and check whether the ranking survives a different start year. You keep working in ~/energy-demo; new outputs go into summary/, where part 6 picks them up for charts.

Like part 4, the numbers printed here come from clean/energy_africa.parquet, the table of all 57 African countries that part 3 saved for regional totals, including South Sudan and Western Sahara, which part 2's coverage rule drops. That keeps the regional figures identical to the ones part 4 checked against the Africa (Ember) total. Do not swap in part 3's 55-country clean/energy_regions.parquet here: it lacks South Sudan and Western Sahara and treats Lesotho's zeros as gaps, so several regional figures below would come out a little different.

Step 1 · Check the regional table has no holes

Every measure in this part compares one year with another. If a year is missing from the middle of a series, "the previous row" is no longer "the previous year", and a two-year jump gets reported as one. So before any arithmetic, check the input: one row per subregion per year, and no skipped years.

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

ry = pd.read_parquet("summary/region_year.parquet").sort_values(["subregion", "year"])
print("rows:", len(ry))
print(ry.groupby("subregion")["year"].agg(["min", "max", "count"]).to_string())

steps = ry.groupby("subregion")["year"].diff().dropna()
print("years skipped inside a series:", int((steps != 1).sum()))
PY
uv run inspect_growth_input.py

diff() inside each group gives the gap between one year and the next. Every gap should be exactly 1.

Check it worked

check_raw.py prints OK twice. The script prints rows: 125, then five lines that each read 2000 2024 25, and finally years skipped inside a series: 0. If you see a skipped year, go back to part 4 and find out why that subregion lost a year before you measure anything.

Step 2 · Compute year-on-year change

Year-on-year change is this year's value divided by last year's, minus one, as a percentage. pct_change() does it in one call. Run it inside groupby("subregion") so each subregion is compared only with itself:

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

ry = pd.read_parquet("summary/region_year.parquet").sort_values(["subregion", "year"])

# Wrong: one long column, so Middle Africa 2000 is compared with Eastern Africa 2024.
wrong = ry["kwh_per_person"].pct_change() * 100
first_middle = (ry["subregion"] == "Middle Africa") & (ry["year"] == 2000)
print(f"without groupby, Middle Africa 2000: {wrong[first_middle].iloc[0]:+.1f}%")

# Right: each subregion against its own previous year.
ry["yoy_pct"] = ry.groupby("subregion")["kwh_per_person"].pct_change() * 100
print(f"with groupby, first-year values that are NaN: {int(ry.loc[ry['year'] == 2000, 'yoy_pct'].isna().sum())} of 5")
print()

for name, g in ry.dropna(subset=["yoy_pct"]).groupby("subregion"):
    up = g.loc[g["yoy_pct"].idxmax()]
    down = g.loc[g["yoy_pct"].idxmin()]
    print(f"{name:16} biggest rise {up['year']:.0f} {up['yoy_pct']:+5.1f}%   biggest fall {down['year']:.0f} {down['yoy_pct']:+5.1f}%")
PY
uv run yoy.py

The first line shows the trap. Sorted by subregion, the row before Middle Africa's 2000 is Eastern Africa's 2024, so a plain pct_change() reports a 44 per cent collapse that never happened. Inside the group, 2000 has no previous year and gets NaN, which is the honest answer.

Year-on-year change is noisy. Western Africa swings from a 9.3 per cent fall in 2003 to a 16.7 per cent rise in 2010. A single year is often a drought that cuts hydropower, a new plant coming online, or a revision in the source, so do not build a headline on one year's change.

Check it worked

The first line reads without groupby, Middle Africa 2000: -44.2% and the second with groupby, first-year values that are NaN: 5 of 5. The five subregion lines include Western Africa biggest rise 2010 +16.7% biggest fall 2003 -9.3% and Northern Africa biggest rise 2012 +9.7% biggest fall 2020 -4.3%.

Step 3 · Compute the compound annual growth rate

To sum up 24 years of change in one number, use the compound annual growth rate: the steady yearly rate that would take the 2000 value to the 2024 value.

CAGR = (end ÷ start) ^ (1 ÷ steps) − 1

The number of steps is the gap between the years, 2024 − 2000 = 24, not the 25 values in the series. Divide by 25 and every rate comes out a little low: Western Africa would show 2.00 per cent a year instead of 2.09. pivot puts each year in its own column, which makes the formula read like the maths:

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

START, END = 2000, 2024
steps = END - START  # 24 steps between 25 yearly values

ry = pd.read_parquet("summary/region_year.parquet")
wide = ry.pivot(index="subregion", columns="year", values="kwh_per_person")

ratio = wide[END] / wide[START]
table = pd.DataFrame({
    f"kwh_{START}": wide[START],
    f"kwh_{END}": wide[END],
    "total_change_pct": (ratio - 1) * 100,
    "cagr_pct": (ratio ** (1 / steps) - 1) * 100,
})
print(table.round(2).to_string())
table.to_csv("summary/region_cagr.csv")

# Compounding the rate forward from the start must land on the end value.
back = wide[START] * (1 + table["cagr_pct"] / 100) ** steps
print(f"largest gap after compounding forward: {(back - wide[END]).abs().max():.6f} kWh")
PY
uv run cagr.py

The last line is a check you can reuse on any growth rate: compound it forward and you should land back on the end value.

Read the two change columns together. Northern Africa's electricity per person more than doubled (+104.7 per cent), which is 3.03 per cent a year. Western Africa's rose by 64 per cent, or 2.09 per cent a year. Southern Africa is the only subregion that fell: 3,989 kWh per person in 2000, 3,462 in 2024, a CAGR of −0.59 per cent.

A CAGR uses only the two end points. It says nothing about the path between them, and a bad start or end year moves it a lot. The last two steps of this part come back to that.

Check it worked

The table has five rows. Northern Africa reads about 803.8 1645.7 104.7 3.03 and Southern Africa 3988.6 3461.9 -13.2 -0.59. The last line reads largest gap after compounding forward: 0.000000 kWh, and summary/region_cagr.csv exists.

Step 4 · Build an index with 2000 as 100

Southern Africa generates about 16 times as much per person as Western Africa, so on one chart of raw values the smaller series look flat. An index divides every value by the subregion's own 2000 value and multiplies by 100. Every series then starts at 100, and 150 means "half as much again as in 2000", whatever the starting size.

Index all three parts of the per-person figure: generation, population and the ratio between them.

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

BASE_YEAR = 2000

ry = pd.read_parquet("summary/region_year.parquet").sort_values(["subregion", "year"])
base = ry[ry["year"] == BASE_YEAR].set_index("subregion")

for column, name in [
    ("generation_twh", "generation_index"),
    ("population", "population_index"),
    ("kwh_per_person", "kwh_index"),
]:
    ry[name] = ry[column] / ry["subregion"].map(base[column]) * 100

latest = ry[ry["year"] == 2024].set_index("subregion")
latest = latest[["generation_index", "population_index", "kwh_index"]]
print("2024, with 2000 = 100")
print(latest.round(1).to_string())
latest.to_csv("summary/region_index_2024.csv")

# Per person is generation over population, so the indexes must agree.
gap = latest["generation_index"] / latest["population_index"] * 100 - latest["kwh_index"]
print(f"largest gap, generation index / population index against kWh index: {gap.abs().max():.6f}")
PY
uv run index.py

map(base[column]) looks up each row's subregion in the 2000 values, so each row is divided by its own subregion's base year. Picking the base year by value, rather than taking the first row of each group, means the script still uses 2000 if you later filter the table to start elsewhere.

The three columns tell a story the per-person figure hides. Western Africa generated three times as much electricity in 2024 as in 2000 (308), but its population nearly doubled (188), so per person it rose by 64 per cent (164). Southern Africa generated 18 per cent more, while its population grew 36 per cent, so per person it fell. Neither region's power stations went backwards; the denominator moved. On prepaid electricity or a shared meter, this is the difference between the grid growing and each household getting more of it. Part 7 looks at this more closely.

Check it worked

The table prints three index columns for 2024. Western Africa reads about 308.4 187.9 164.1 and Southern Africa 118.2 136.2 86.8. Every kwh_index is the same ratio as in the CAGR step: Western Africa's 164.1 matches its total change of +64.1 per cent. The last line ends in 0.000000.

Step 5 · Smooth the series with a three-year rolling mean

A rolling mean replaces each value with the average of a window of values around it. With a window of three, the 2024 value becomes the mean of 2022, 2023 and 2024. One unusual year then moves the line by a third as much.

rolling(3) uses a trailing window, the current year and the two before it. Wrap it in groupby(...).transform so no window crosses from one subregion into the next. Then measure how much it calms the series by comparing the spread of year-on-year changes before and after:

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

ry = pd.read_parquet("summary/region_year.parquet").sort_values(["subregion", "year"])
by_region = ry.groupby("subregion")["kwh_per_person"]

# Trailing window: this year and the two before it, never across subregions.
ry["kwh_rolling3"] = by_region.transform(lambda s: s.rolling(3).mean())
ry["yoy_raw"] = by_region.pct_change() * 100
ry["yoy_smoothed"] = ry.groupby("subregion")["kwh_rolling3"].pct_change() * 100

west = ry[ry["subregion"] == "Western Africa"].set_index("year")
print("Western Africa, kWh per person")
print(west.loc[2020:, ["kwh_per_person", "kwh_rolling3"]].round(1).to_string())
print()

spread = ry.groupby("subregion")[["yoy_raw", "yoy_smoothed"]].std()
print("standard deviation of year-on-year change, in percentage points")
print(spread.round(2).to_string())
spread.to_csv("summary/region_yoy_spread.csv")
print()
print("rolling values missing in 2000 and 2001:", int(ry["kwh_rolling3"].isna().sum()))
PY
uv run rolling.py

In 2024 Western Africa's raw value fell 6.3 per cent, from 231.0 to 216.5 kWh per person. The rolling mean dips only from 225.3 to 223.6. Which one to report depends on the question. For "what happened in 2024", use the raw value. For "which way is the trend going", use the smoothed line and say it is a three-year average.

Two cautions. A trailing mean lags: a real turn shows up in it a year or so late. A centred window, rolling(3, center=True), does not lag, but it needs next year's value too, so it has nothing to say about 2024 until the 2025 data is complete. Either way, the first two years have no value, which is why the last line counts 10 missing values: two for each of the five subregions.

Check it worked

The Western Africa table ends with 2023 231.0 225.3 and 2024 216.5 223.6. In the spread table every yoy_smoothed value is smaller than yoy_raw; Western Africa drops from about 6.68 to 2.77. The last line reads rolling values missing in 2000 and 2001: 10.

Step 6 · Measure the renewables share in percentage points

The renewables share is already a percentage. When a percentage changes, there are two ways to describe it, and they can sound wildly different:

  • Percentage points are the plain difference: a share going from 30 per cent to 40 per cent is a rise of 10 points.
  • Percent change is the relative change: the same move is a rise of 33 per cent.

Compute both, plus the renewable generation behind the share, so you can see what each one hides:

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

START, END = 2000, 2024

ry = pd.read_parquet("summary/region_year.parquet")
share = ry.pivot(index="subregion", columns="year", values="renewables_share_pct")
twh = ry.pivot(index="subregion", columns="year", values="renewables_twh")

table = pd.DataFrame({
    f"share_{START}": share[START],
    f"share_{END}": share[END],
    "change_points": share[END] - share[START],
    "relative_change_pct": (share[END] / share[START] - 1) * 100,
    f"renewables_twh_{START}": twh[START],
    f"renewables_twh_{END}": twh[END],
})
print(table.round(1).to_string())
table.to_csv("summary/region_share_change.csv")
PY
uv run share.py

Southern Africa's share went from 1.8 to 13.1 per cent. That is a rise of 11.3 percentage points, or 616 per cent. Both are arithmetically true, but "renewables up 616 per cent" says more about how small the starting share was than about the electricity system. Report shares in points, and if you also give a relative change, name it as such.

Western Africa shows the opposite trap. Its share fell by 17.6 points, from 46.7 to 29.1 per cent, yet its renewable generation almost doubled, from 14.9 to 28.7 TWh. Generation from other sources grew faster still. A falling share does not mean renewables shrank, so keep the TWh columns next to any share you report.

Check it worked

Southern Africa's row reads about 1.8 13.1 11.3 615.8 3.9 33.2. Western Africa shows -17.6 points, -37.6 per cent, and renewable generation rising from 14.9 to 28.7 TWh. summary/region_share_change.csv exists.

Step 7 · Find the fastest and slowest growing countries

Regional figures are dominated by the largest countries. To see who moved most, compute the same CAGR for each country. Put the country-level code in a small module, country_growth.py, because the next step uses it too.

Part 2 decided that a value of exactly 0 for a populated country is a gap, not a fact. The 57-country table from part 3's join still holds Lesotho's 2024 value as 0 kWh per person, which would give it a growth rate of −100 per cent. The module treats zeros as missing, so it gives the same result whether or not your file already has part 2's zeros replaced:

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

END = 2024


def kwh_by_country():
    """One row per country, one column per year, kWh per person; zeros become NaN."""
    df = pd.read_parquet("clean/energy_africa.parquet")
    df = df[df["year"] <= END]
    kwh = df["generation_kwh_per_person"]
    df = df.assign(kwh=kwh.where(kwh > 0))  # part 2: a zero is a gap
    return df.pivot(index="country", columns="year", values="kwh")


def cagr(wide, start, end=END):
    """Compound annual growth in percent, for countries with both years."""
    both = wide[[start, end]].dropna()
    return ((both[end] / both[start]) ** (1 / (end - start)) - 1) * 100
PY
cat > countries.py <<'PY'
from country_growth import cagr, kwh_by_country

wide = kwh_by_country()
growth = cagr(wide, 2000).rename("cagr_pct").sort_values(ascending=False)

print("countries with values in 2000 and 2024:", len(growth))
print("left out:", ", ".join(sorted(set(wide.index) - set(growth.index))))
print()
print("fastest, % a year")
print(growth.head(5).round(2).to_string())
print()
print("slowest, % a year")
print(growth.tail(5).round(2).to_string())
growth.to_csv("summary/country_cagr_2000_2024.csv")
PY
uv run countries.py

Eight countries drop out, each for a reason you have met before: South Sudan has no values before 2012, Western Sahara has none after 2009, Lesotho's 2024 value is a zero, and five small places have no 2024 figures yet. Write the list down; a ranking that silently skips countries is easy to misread.

The fastest growers, Equatorial Guinea, Congo and Ethiopia, grew by between 8.8 and 10.5 per cent a year, enough to multiply electricity per person by between seven and eleven over 24 years. Several started from very low levels, and a low base makes high rates easy. The slowest, with Djibouti and Namibia at the bottom, fell slightly per person.

Small countries also carry a quieter problem. The file gives generation in TWh to two decimal places, so Sierra Leone's 0.09 TWh in 2000 could be anything from 0.085 to 0.095: an uncertainty of about 5 per cent in its starting value before any real change. Treat tiny-country rates as rough.

Check it worked

The first line reads countries with values in 2000 and 2024: 49, and the second lists the eight countries above. The fastest list starts with Equatorial Guinea at about 10.54, then Congo and Ethiopia. The slowest list ends with Djibouti and then Namibia at about -1.57.

Step 8 · Check whether the start year changes the ranking

Any growth rate depends on its start year. Choose 2000 and you get one ranking; choose a year when a country was at a low point and that country looks like a star. Before you publish a ranking, recompute it from other start years and see how much it moves.

Rank the countries by CAGR from 2000, 2005 and 2010, all to 2024. The correlation between two sets of ranks (Spearman's rank correlation) is 1 when the order is identical and falls as countries swap places. Computing it as the ordinary correlation of the ranks avoids an extra dependency:

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

from country_growth import cagr, kwh_by_country

STARTS = [2000, 2005, 2010]

wide = kwh_by_country()
rates = pd.DataFrame({start: cagr(wide, start) for start in STARTS}).dropna()
ranks = rates.rank(ascending=False)  # 1 = fastest
print("countries compared:", len(rates))

top_2000 = set(ranks.index[ranks[2000] <= 10])
for start in STARTS[1:]:
    rho = ranks[2000].corr(ranks[start])  # correlation of ranks = Spearman
    top = set(ranks.index[ranks[start] <= 10])
    print(f"from {start}: rank correlation with 2000 = {rho:.3f}, top ten shared = {len(top & top_2000)} of 10")
    print("   joins the top ten:", ", ".join(sorted(top - top_2000)))
    print("   leaves the top ten:", ", ".join(sorted(top_2000 - top)))

moves = (ranks[2000] - ranks[2010]).abs().sort_values(ascending=False, kind="stable")
print()
print("biggest moves, rank by start year")
print(ranks.loc[moves.index[:4]].astype(int).to_string())
ranks.astype(int).to_csv("summary/country_rank_by_start_year.csv")
PY
uv run start_year.py

The broad picture holds: a rank correlation of 0.92 from 2005 and 0.84 from 2010 means most countries stay near where they were, and Equatorial Guinea, Congo and Benin are in the top five whichever year you start from. Individual places are another matter. Botswana is 21st from 2000 but 2nd from 2010, because 2010 fell in a slump in its own generation: 261 kWh per person, against 680 in 2000 and 1,360 in 2024, with the lowest point, 166, in 2012. Guinea-Bissau and Liberia also climb by 17 places or more, while Sudan goes the other way, from 7th to 24th.

So "Botswana is one of Africa's fastest growers" is true only for one choice of start year. Two habits protect you. Choose the start year for a reason you can state before you look at the results (here, Ember's coverage begins in 2000). And when you report a ranking, say how it changes with another start year, or measure from three-year averages at each end so a single unusual year carries less weight.

Check it worked

The script prints countries compared: 49, then from 2005: rank correlation with 2000 = 0.922, top ten shared = 7 of 10 and from 2010: rank correlation with 2000 = 0.837, top ten shared = 6 of 10. From 2010, Botswana, Burundi, Niger and Togo join the top ten, and Angola, Cape Verde, Senegal and Sudan leave it. The last table lists four countries, in order Botswana (21 10 2), Guinea-Bissau (31 22 12), Liberia (32 21 15) and Sudan (7 12 24). Moves of the same size are listed alphabetically, because the sort is stable.

Step 9 · Save the growth table and record the decisions

Part 6 charts these measures. Save them in one tidy table, one row per subregion and year, so the charts read a single file instead of re-deriving anything. Then add this part's decisions to notes.md:

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

ry = pd.read_parquet("summary/region_year.parquet").sort_values(["subregion", "year"])
by_region = ry.groupby("subregion")
base = ry[ry["year"] == 2000].set_index("subregion")

ry["yoy_pct"] = by_region["kwh_per_person"].pct_change() * 100
ry["kwh_index_2000"] = ry["kwh_per_person"] / ry["subregion"].map(base["kwh_per_person"]) * 100
ry["kwh_rolling3"] = by_region["kwh_per_person"].transform(lambda s: s.rolling(3).mean())
ry["share_change_points"] = ry["renewables_share_pct"] - ry["subregion"].map(base["renewables_share_pct"])

columns = ["subregion", "year", "kwh_per_person", "yoy_pct", "kwh_index_2000",
           "kwh_rolling3", "renewables_share_pct", "share_change_points"]
ry[columns].to_parquet("summary/region_growth.parquet", index=False)
print("rows:", len(ry), "columns:", len(columns))
PY
uv run build_growth.py
cat >> notes.md <<'MD'

## Part 5: change over time

- Measures are per subregion: year-on-year change and rolling means run inside groupby, so no
  comparison crosses from one subregion into another.
- CAGR uses steps between years (2024 - 2000 = 24), not the number of values (25).
- kWh per person 2000 to 2024: Northern Africa +104.7% (3.03% a year), Western Africa +64.1%
  (2.09%), Southern Africa -13.2% (-0.59%), the only fall. Southern Africa generated 18% more but
  its population grew 36%.
- Smoothing: trailing three-year mean; label it as such. No value for 2000 and 2001.
- Shares are reported in percentage points. Southern Africa renewables +11.3 points (616% relative,
  from a 1.8% base). Western Africa -17.6 points while renewable TWh almost doubled.
- Country CAGR: 49 countries with values in 2000 and 2024; zeros treated as missing (Lesotho 2024).
  Eight of the 57 left out: CAF, Comoros, Lesotho, Reunion, Saint Helena, Sao Tome and Principe,
  South Sudan, Western Sahara.
- Start year: rank correlation with the 2000 ranking 0.92 from 2005, 0.84 from 2010. Botswana is 21st
  from 2000 but 2nd from 2010 (2010 fell in a slump that bottomed out in 2012). Report rankings with this caveat.
- Output for part 6: summary/region_growth.parquet.
MD
ls summary

Check it worked

The script prints rows: 125 columns: 8. ls summary lists the four files from part 4 plus seven new ones: country_cagr_2000_2024.csv, country_rank_by_start_year.csv, region_cagr.csv, region_growth.parquet, region_index_2024.csv, region_share_change.csv and region_yoy_spread.csv. Open notes.md and check each figure in the new section against what your scripts printed.

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.