Lesson 56 · Real-World Data Analytics
Pandas pivot for Change Over Time: Renewable Energy Analysis | Python Data Analytics #56
Moving this domain from real land cover into real energy production. A real sustainable-energy dataset, honestly scoped to the real first eighteen countries…
- CourseReal-World Data Analytics
- Lesson56 of 100
- Video18 min
- FormatJupyter notebook · 30 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- sustainable_energy.csv preview53.3 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 56: Real Global Renewable Energy Analysis#
- Video fifty-six of the hundred-video real-world data analytics series, moving this domain from real land cover into real energy production.
- A real sustainable-energy dataset, honestly scoped to the real first eighteen countries alphabetically, Afghanistan through Belize, across the real full 2000 through 2020 span.
- Let's get into it.
This lesson is for learners who want to practise a complete exploratory analysis on a real public dataset with a sustainability angle. The business question is simple to state: which countries are getting their energy from renewable sources, how has that changed since 2000, and does a country's wealth predict its energy mix?
The data is a sustainable-energy file, sustainable_energy.csv, with one row per country per year. The columns that matter most here are access_electricity_pct (share of people with electricity), renewable_share_pct (renewables as a share of final energy consumption), elec_fossil_twh and elec_renewables_twh (electricity generated, in terawatt-hours), low_carbon_elec_pct, co2_emissions_kt and gdp_per_capita. The notebook works with an honestly scoped slice: the first 18 countries alphabetically, Afghanistan to Belize, for 2000 to 2020.
In this lesson you will:
- audit missing values and spot a reporting lag in the latest year
- rank countries for a single year and measure change over time with
pivot - compare fossil and renewable electricity for one country
- check a correlation and save an enriched file
You should be comfortable with pandas filtering, sort_values and basic matplotlib bar charts; see earlier lessons in the series if not.
Part 1: A Real Sustainable Energy Dataset#
Every analysis starts by loading the data and checking its size, so you know what you are working with before you trust any result. The code imports pandas, numpy and matplotlib, reads sustainable_energy.csv with pd.read_csv, and asks for .shape. The output is (378, 21): 378 rows and 21 columns. That row count is worth remembering, because 18 countries times 21 years is exactly 378, which suggests one row per country per year with nothing missing or doubled. A later sanity check confirms this.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
energy = pd.read_csv('sustainable_energy.csv')
energy.shape
Part 2: Real Data Preview#
Before analysing anything you need to see what the columns are called and what typical values look like. The code lists the column names with .columns.tolist(), then shows the first three rows with .head(3). Because Jupyter only displays the last expression, the output you see is the head table, not the list. It shows Afghanistan for 2000 to 2002, with electricity access rising from about 1.6% to 9.4% and a renewable share around 38% to 46%. Notice the NaN values in columns such as renewables_equiv_primary_pct and gdp_per_capita: missing data is already visible.
energy.columns.tolist()
energy.head(3)
Part 3: Real Missing Data Check#
Missing values decide which questions you can answer, so you audit them early. energy.isna().sum() counts the empty cells in each column. The core columns (country, year, access_electricity_pct, the electricity TWh columns) are complete. Others are patchy: renewables_equiv_primary_pct is missing in 210 of 378 rows, financial_flows_usd in 251, renewable_capacity_per_capita in 105, and the key metric renewable_share_pct in 38. A tip: a column missing more than half its values, like financial_flows_usd, is usually best left out of headline findings.
energy.isna().sum()
Part 4: Real Duplicate Row Check#
Duplicate rows would double-count a country's year and skew every average, so it is worth a quick check. energy.duplicated().sum() marks each row that is an exact copy of an earlier one and adds up those True values. The output is 0, so there are no fully duplicated rows. Note that duplicated() only catches rows identical in every column; if you want to check that each country and year pair appears once, pass subset=['country', 'year'].
energy.duplicated().sum()
Part 5: Real Honest Scope Check#
You should confirm the scope of the data before you describe it, so you never claim it covers more than it does. The code checks how many countries there are with .nunique() and lists them with sorted(...unique()), then finds the earliest and latest year with .min() and .max(). Only the last line is displayed, so the output shows the years only: 2000 to 2020. The country count is confirmed later in the recap print as 18. Being explicit about scope like this keeps your conclusions honest.
energy['country'].nunique(), sorted(energy['country'].unique())
energy['year'].min(), energy['year'].max()
Part 6: Real Electricity Access in 2020#
Electricity access is a basic development indicator, and 2020 is the latest year available, so it is a natural place to start comparing countries. The code filters to year == 2020, keeps the country and access_electricity_pct columns, and sorts from lowest to highest with sort_values. The output shows Angola far behind at about 46.9%, followed by Bangladesh (96.2%), Belize (97.1%) and Afghanistan (97.7%). Most of the other countries sit at 100%. Sorting ascending puts the countries that need attention at the top of the table.
access_2020 = energy[energy['year'] == 2020][['country', 'access_electricity_pct']].sort_values('access_electricity_pct')
access_2020
Part 7: Real Electricity Access Chart#
A chart makes the gap between Angola and the rest obvious at a glance. The code creates a figure with plt.subplots(figsize=(10, 7)) and draws a horizontal bar chart with ax.barh, which suits long country names. It labels the axis and title, uses tight_layout() so labels are not cut off, saves the image with savefig and then calls plt.close(), so no chart is displayed in the notebook. When you open the saved file, look for one short bar for Angola against a wall of bars reaching 100%.
fig, ax = plt.subplots(figsize=(10, 7))
ax.barh(access_2020['country'], access_2020['access_electricity_pct'], color='steelblue')
ax.set_xlabel('Real Percent of Population with Electricity Access')
ax.set_title('Real Electricity Access by Country, 2020')
plt.tight_layout()
plt.savefig('electricity_access_2020.png', dpi=100)
plt.close()
Part 8: Real 2020 Renewable Share Gap#
Before ranking renewable share for 2020, you check whether the 2020 values actually exist. The code filters to 2020 rows, selects renewable_share_pct, and counts missing values with .isna().sum(). The output is 18, which means every one of the 18 countries is missing this metric in 2020. That accounts for 18 of the 38 missing values found earlier. This is a reporting lag in the source data, not a mistake in your code, so the sensible move is to use 2019 as the latest usable year for renewable share.
energy[energy['year'] == 2020]['renewable_share_pct'].isna().sum()
Part 9: Real 2019 Renewable Share Ranking#
With 2020 empty, 2019 becomes the year for comparing renewable share across countries. The code filters to 2019, keeps two columns, drops rows with missing values using .dropna(), and sorts from highest to lowest with ascending=False. The output lists 17 countries, so one country has no 2019 value. Angola leads at 54.69%, followed by Austria (33.77%) and Belize (29.09%). Bahrain reports 0.00%, and Algeria only 0.16%. Remember this measures renewables as a share of all final energy use, not just electricity.
share_2019 = energy[energy['year'] == 2019][['country', 'renewable_share_pct']].dropna().sort_values('renewable_share_pct', ascending=False)
share_2019
Part 10: Real Renewable Share Chart#
This chart shows the same 2019 ranking visually, so the spread between leaders and laggards is easy to see. The code reuses the plt.subplots and ax.barh pattern with a green colour and saves the image as renewable_share_2019.png; plt.close() means nothing is shown inline. In the saved chart, look for Angola's bar standing well clear of the rest, then a cluster of countries between about 10% and 34%, and a long tail of countries near zero. Because the data was sorted descending, the largest bar is drawn at the bottom of a barh chart.
fig, ax = plt.subplots(figsize=(10, 7))
ax.barh(share_2019['country'], share_2019['renewable_share_pct'], color='seagreen')
ax.set_xlabel('Real Renewable Share of Final Energy Consumption, Percent')
ax.set_title('Real Renewable Energy Share by Country, 2019')
plt.tight_layout()
plt.savefig('renewable_share_2019.png', dpi=100)
plt.close()
Part 11: Real Renewable Share Change, 2000 to 2019#
A single year tells you where countries stand; change over time tells you which way they are moving. The code uses pivot to reshape the long table into one row per country and one column per year, with renewable share as the values. Subtracting the 2000 column from the 2019 column gives the change in percentage points, then .dropna() removes countries missing either year and .sort_values() orders the result. The output shows Bangladesh fell by 34.31 points and Afghanistan by 26.48, while Belgium (+8.77) and Austria (+7.33) gained the most. A falling share can happen when total energy use grows faster than renewables.
share_pivot = energy.pivot(index='country', columns='year', values='renewable_share_pct')
share_change = (share_pivot[2019] - share_pivot[2000]).dropna().sort_values()
share_change
Part 12: Real Renewable Share Change Chart#
Colour-coding gains and losses helps the reader see the direction of change instantly. The code builds a list called colors with a list comprehension, choosing firebrick when a value is below zero and seagreen otherwise, and passes it to ax.barh. The image is saved as renewable_share_change.png and the figure is closed, so there is no inline output. In the saved chart, look for five clear red bars (Bangladesh, Afghanistan, Angola, Barbados, Belize) against mostly small green gains. Small values like Azerbaijan's -0.45 will look almost flat.
fig, ax = plt.subplots(figsize=(10, 7))
colors = ['firebrick' if v < 0 else 'seagreen' for v in share_change]
ax.barh(share_change.index, share_change.values, color=colors)
ax.set_xlabel('Real Percentage-Point Change in Renewable Share, 2000-2019')
ax.set_title('Real Renewable Share Change by Country')
plt.tight_layout()
plt.savefig('renewable_share_change.png', dpi=100)
plt.close()
Part 13: Real Renewable Electricity Growth in Terawatt-Hours#
Share is relative, so it is useful to also look at absolute growth in renewable electricity. The code pivots elec_renewables_twh by country and year, subtracts 2000 from 2020, and sorts descending. There is no dropna here because these columns are complete. The output shows Australia added 46.88 terawatt-hours (TWh, a unit of electricity), well ahead of Belgium (22.41) and Austria (11.98). Azerbaijan is the only country that fell, by 0.30 TWh. Large economies naturally dominate absolute numbers, so read this alongside the share results rather than instead of them.
elec_pivot = energy.pivot(index='country', columns='year', values='elec_renewables_twh')
elec_growth = (elec_pivot[2020] - elec_pivot[2000]).sort_values(ascending=False)
elec_growth
Part 14: Real Electricity Growth Chart#
This chart turns the absolute growth table into a picture, which makes Australia's lead stand out. The code draws an orange horizontal bar chart from the elec_growth series, using the index for country names and .values for the bar lengths, then saves it as renewable_electricity_growth.png and closes the figure. Nothing appears inline. In the saved chart, look for one long bar for Australia, a few medium bars for Belgium, Austria and Angola, and most other countries clustered near zero.
fig, ax = plt.subplots(figsize=(10, 7))
ax.barh(elec_growth.index, elec_growth.values, color='darkorange')
ax.set_xlabel('Real Growth in Renewable Electricity, Terawatt-Hours, 2000-2020')
ax.set_title('Real Renewable Electricity Growth by Country')
plt.tight_layout()
plt.savefig('renewable_electricity_growth.png', dpi=100)
plt.close()
Part 15: Real CO2 Emissions Ranking#
Emissions give the other side of the energy story: renewables matter because fossil fuels release CO2. The code filters to 2019, keeps country and co2_emissions_kt (kilotonnes, thousands of tonnes), drops missing values and sorts largest first. The output lists 16 countries, so two have no 2019 figure. Australia is far ahead at about 386,530 kt, followed by Algeria (about 171,250) and Argentina (about 168,100). Antigua and Barbuda is lowest at about 520 kt. These are totals, not per person, so population size drives much of the ranking.
co2_2019 = energy[energy['year'] == 2019][['country', 'co2_emissions_kt']].dropna().sort_values('co2_emissions_kt', ascending=False)
co2_2019
Part 16: Real CO2 Emissions Chart#
A bar chart of emissions shows how concentrated they are among a few countries. The code repeats the horizontal bar pattern in grey, labels the axis in kilotons and saves the figure as co2_emissions_2019.png before closing it, so there is no inline output. In the saved chart, look for Australia's bar being more than twice the next country, and for the smaller countries whose bars are so short they are hard to see. A log scale would help if you wanted to compare those small values.
fig, ax = plt.subplots(figsize=(10, 7))
ax.barh(co2_2019['country'], co2_2019['co2_emissions_kt'], color='dimgray')
ax.set_xlabel('Real CO2 Emissions, Kilotons')
ax.set_title('Real CO2 Emissions by Country, 2019')
plt.tight_layout()
plt.savefig('co2_emissions_2019.png', dpi=100)
plt.close()
Part 17: Real GDP vs Renewable Share Correlation#
A common assumption is that richer countries use more renewable energy. This step tests that idea with a correlation, a number from -1 to 1 that measures how closely two variables move together in a straight line. The code filters to 2019 and uses Series.corr to compare gdp_per_capita with renewable_share_pct, rounding to four decimals. pandas ignores rows where either value is missing. The output is -0.0602, which is essentially zero: in this subset, wealth does not predict renewable share. With fewer than 18 countries, treat this as a hint rather than a firm conclusion.
d2019 = energy[energy['year'] == 2019]
gdp_corr = round(d2019['gdp_per_capita'].corr(d2019['renewable_share_pct']), 4)
gdp_corr
Part 18: Real Renewable Share Trend Over Time#
Averaging across countries shows whether the group as a whole is moving towards renewables. The code groups by year and takes the .mean() of renewable_share_pct, which skips missing values. The output starts at about 16.9% in 2000, drifts down to about 13.1% by 2009, and ends at about 13.3% in 2019. The 2020 value is NaN because every country is missing that year. Keep in mind that a simple average gives Aruba the same weight as Australia, so it describes typical countries rather than total energy use.
yearly_avg = energy.groupby('year')['renewable_share_pct'].mean()
yearly_avg
Part 19: Real Trend Chart#
A line chart is the clearest way to show a trend over time. The code calls .dropna() on the yearly averages to remove the empty 2020 value, then uses the pandas .plot method with marker='o' so each year is shown as a dot on the line. The figure is saved as renewable_share_trend.png and closed, so there is no inline output. In the saved chart, look for a gentle decline through the 2000s and a fairly flat line after about 2010, rather than a steady rise.
fig, ax = plt.subplots(figsize=(10, 6))
yearly_avg.dropna().plot(ax=ax, marker='o', color='seagreen')
ax.set_xlabel('Real Year')
ax.set_ylabel('Real Average Renewable Share, Percent')
ax.set_title('Real Average Renewable Share Across This Subset, 2000-2019')
plt.tight_layout()
plt.savefig('renewable_share_trend.png', dpi=100)
plt.close()
Part 20: Real Fossil vs Renewable Mix for Australia#
Zooming into one country helps you see the electricity transition in more detail. Australia added the most renewable electricity, so it makes a good case study. The code filters to Australia and keeps the year plus fossil and renewable generation, then shows the last five rows with .tail(5). The output shows fossil generation falling from 207.66 TWh in 2016 to 186.92 in 2020, while renewables rose from 38.41 to 63.99 TWh. Renewables are growing quickly, but fossil fuels still produce roughly three times as much.
aus = energy[energy['country'] == 'Australia'][['year', 'elec_fossil_twh', 'elec_renewables_twh']]
aus.tail(5)
Part 21: Real Australia Mix Chart#
Plotting both sources on the same axes shows how the gap between them changes. The code calls ax.plot twice, once for fossil and once for renewables, each with a label, and ax.legend() uses those labels to build a key. The figure is saved as australia_mix.png and closed, so nothing is shown inline. In the saved chart, look for the grey fossil line flattening and dropping towards the end, and the green renewable line climbing faster in the last few years. A common mistake is forgetting label=, which leaves the legend empty.
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(aus['year'], aus['elec_fossil_twh'], label='Real Fossil', color='dimgray')
ax.plot(aus['year'], aus['elec_renewables_twh'], label='Real Renewables', color='seagreen')
ax.set_xlabel('Real Year')
ax.set_ylabel('Real Terawatt-Hours')
ax.set_title('Real Australia Electricity Mix, 2000-2020')
ax.legend()
plt.tight_layout()
plt.savefig('australia_mix.png', dpi=100)
plt.close()
Part 22: Real Low-Carbon Electricity Share in 2020#
Renewable share covers all energy, but low-carbon electricity share focuses on the power sector and includes nuclear as well as renewables. It is also complete for 2020, so you can use the latest year. The code filters to 2020 and sorts low_carbon_elec_pct descending. The output shows Albania at 100%, Afghanistan at 85% and Austria at about 80.1%. At the bottom, Bahrain is about 0.03% and Bahamas 0%. Note how different this ranking is from renewable share: Bangladesh scores 24.75% on renewable share in 2019 but under 2% on low-carbon electricity.
low_carbon_2020 = energy[energy['year'] == 2020][['country', 'low_carbon_elec_pct']].sort_values('low_carbon_elec_pct', ascending=False)
low_carbon_2020
Part 23: Real Electricity Access Category#
Grouping countries into categories makes results easier to report than a list of percentages. The code first takes a .copy() of the 2020 rows, which avoids pandas warnings when you add a column to a filtered table. np.where then labels each country full_access when access is 99% or more, and partial_access otherwise. The output shows Angola, Afghanistan, Bangladesh and Belize as partial_access. Algeria, at about 99.8%, counts as full access because of the 99% threshold, so be clear about where you set the cut-off when you share results.
d2020 = energy[energy['year'] == 2020].copy()
d2020['access_category'] = np.where(d2020['access_electricity_pct'] >= 99, 'full_access', 'partial_access')
d2020[['country', 'access_electricity_pct', 'access_category']]
Part 24: Real Access Category Count#
Once you have a category, the next question is how many fall into each group. value_counts() counts how often each label appears in the access_category column. The output shows 14 countries with full access and 4 with partial access in 2020. This kind of one-line summary is handy for a report or a slide, as long as you also state the threshold behind it.
d2020['access_category'].value_counts()
Part 25: Real Sanity Check, Honest Scope#
Sanity checks confirm the data matches your assumptions, so problems are caught before they spread into results. The code checks that the number of rows equals 18 countries times 21 years. The output is True, so the table holds exactly one row for each country and year combination, which supports the earlier duplicate check. Writing assumptions as small True or False tests like this is a good habit for any analysis you might rerun later.
len(energy) == 18 * 21
Part 26: Saving the Real Enriched Dataset#
Saving your enriched data lets you or a colleague pick up from here without rerunning every step. The code writes the 2020 table, including the new access_category column, with to_csv(..., index=False), which stops pandas from writing the row index as an extra column. It then reads the file back and checks that the reloaded shape matches the original. The output is True, so the file was saved correctly. Forgetting index=False is a common cause of mysterious extra columns when files are reloaded.
d2020.to_csv('sustainable_energy_2020_enriched.csv', index=False)
reloaded = pd.read_csv('sustainable_energy_2020_enriched.csv')
reloaded.shape == d2020.shape
Part 27: Real Sanity Check, Row Count#
This quick test confirms that the 2020 slice contains one row per country. The code checks that len(d2020) equals 18. The output is True, so no country is missing from the latest year and none appears twice. It is a small check, but it protects every 2020 ranking and count you produced from silently leaving a country out.
len(d2020) == 18
Part 28: Real Sanity Check, No Missing Core Columns#
The core columns are the ones every other step depends on, so you confirm they have no gaps. The code selects country, year and access_electricity_pct, counts missing values with .isna().sum(), then adds those counts again with a second .sum() to get one total. Comparing it with 0 gives the output np.True_, numpy's version of True. That means these three columns are fully populated, which matches the missing-value audit at the start.
energy[['country', 'year', 'access_electricity_pct']].isna().sum().sum() == 0
Part 29: Real Top Finding Print#
A clear sentence is often more useful to a stakeholder than a table. The code takes the first row of the sorted 2019 ranking with .iloc[0], which is the top country because the table was sorted descending, and prints it inside an f-string. The output reads that Angola had the highest renewable energy share in 2019, at 54.69 percent of final energy consumption. Building the sentence from the data, rather than typing the numbers by hand, means it stays correct if the data changes.
top_renewable = share_2019.iloc[0]
print(f'The real highest renewable energy share in this honest subset for 2019 belonged to {top_renewable["country"]}, at {top_renewable["renewable_share_pct"]} percent of final energy consumption.')
Part 30: Real Recap Print#
The final print gathers the headline findings into one sentence. The f-string pulls the number of countries and years with .nunique() and reuses the stored gdp_corr value. The output states 18 countries and 21 tracked years, a correlation of -0.0602 between GDP per capita and renewable share, and that Australia added the most renewable electricity in absolute terms. Note that the Australia claim is typed into the text rather than computed, so if you reuse this pattern, pull such facts from the data as well.
print(f'Across {energy["country"].nunique()} real countries and {energy["year"].nunique()} real tracked years, the real correlation between GDP per capita and renewable share was {gdp_corr}, and Australia added the real most renewable electricity in absolute terawatt-hours.')
Wrap-Up: What You Learned#
- This real lesson honestly scoped a real fetch-limited pull from a global sustainable energy dataset down to its real first eighteen countries alphabetically, Afghanistan through Belize, across the real full 2000 through 2020 span.
- Real renewable energy share was genuinely missing for every country in the real most recent 2020 row, a real honest reporting lag rather than a processing mistake, so 2019 stood in as the real last usable year for that metric.
- Angola led this honest subset on real renewable share at 54.69 percent in 2019, while Australia added the real most renewable electricity generation in absolute terawatt-hours.
- Real GDP per capita and real renewable energy share showed essentially real no linear correlation across this honest subset, a genuinely useful real reminder that wealth alone does not predict energy mix.
- Next video: a real global air quality dataset, continuing this domain's look at real environmental measurement.
Practice on your own
- Repeat the 2000 to 2019 change analysis for
low_carbon_elec_pctusingpivot, and compare which countries improved most against the renewable share ranking. - Compute CO2 emissions per person for 2019 by combining
co2_emissions_ktwithenergy_per_capita_kwhor another column you choose, and see whether Australia still tops the list. Note which columns you used and why. - Recalculate the GDP correlation for 2010 and 2015 as well as 2019, and check whether the near-zero result holds across years.
The next lesson in the series moves on to a real global air quality dataset, continuing the look at environmental measurement.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



