Mathew K Analytics

Lesson 55 · Real-World Data Analytics

Read Semicolon CSVs & Percent Change: Forest Cover Analysis | Python Data Analytics #55

Closing out this look at real environmental change with real forest cover. A real two hundred thirty-seven row dataset of real forest area as a percentage…

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.

📓 Full notebook

Download .ipynb

Data Analytics 100, Video 55: Real Global Forest Change Analysis#

  • Video fifty-five of the hundred-video real-world data analytics series, closing out this look at real environmental change with real forest cover.
  • A real two hundred thirty-seven row dataset of real forest area as a percentage of land area, for real individual countries and territories, comparing the real year 2000 to the real year 2020.
  • Let's get into it.

This lesson is for learners who want practice comparing two snapshots in time across many countries, and in telling the difference between relative and absolute change. The question is: how did forest cover change around the world between 2000 and 2020, which places gained or lost the most, and how widespread was the loss?

The dataset has 237 rows: individual countries and territories plus one world aggregate row. The columns are iso3c (the three-letter country code, such as ALB for Albania), forests_2000 and forests_2020 (forest area as a percentage of land area in each year), and trend, the percent change between the two years.

In this lesson you will:

  • load a semicolon-separated file and separate an aggregate row from country rows
  • rank gainers and losers by percent change and by percentage-point change
  • classify countries into severity bands with np.select
  • check how closely 2020 values follow 2000 values with a scatter chart and correlation

Prerequisites: you should be comfortable with pandas filtering, nlargest, groupby and simple matplotlib charts. Earlier lessons in the series cover these if you need a refresher.

Part 1: A Real Forest Cover Dataset#

Loading the file correctly is the first hurdle, because not every CSV uses commas. pd.read_csv is given sep=';' because this file separates values with semicolons, and encoding='utf-8-sig' removes an invisible marker some programs add to the start of a file, which would otherwise end up stuck to the first column name. The output (237, 4) shows 237 rows and 4 columns. If a file loads as a single column, a wrong separator is usually the cause.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
forest = pd.read_csv('forest_shares.csv', sep=';', encoding='utf-8-sig')
forest.shape
(237, 4)

Part 2: Real Data Preview#

A preview tells you what each column holds and how change is measured. The code has two expressions, but Jupyter only displays the last, so you see forest.head(5). Albania (ALB) went from 28.1% to 28.8% forest cover with a trend of 2.5, while Algeria (DZA) went from 0.7% to 0.8% with a trend of 14.3. That contrast shows trend is a relative percent change, so tiny starting values can produce big trend figures.

forest.columns.tolist()
forest.head(5)
iso3c forests_2000 forests_2020 trend
0 AFG 1.9 1.9 0.0
1 ALB 28.1 28.8 2.5
2 DZA 0.7 0.8 14.3
3 ASM 88.7 85.7 -3.4
4 AND 34.0 34.0 0.0

Part 3: Real Missing Data Check#

Missing values affect any ranking or average that uses the affected column. forest.isna().sum() counts NaN cells per column. The output shows the two forest share columns are complete, but trend is missing in 10 rows. A likely reason is that a percent change cannot be calculated when the starting value is zero, since you cannot divide by zero. Always ask why data is missing before deciding how to handle it.

forest.isna().sum()
iso3c            0
forests_2000     0
forests_2020     0
trend           10
dtype: int64

Part 4: Real Duplicate Row Check#

Duplicate rows would let one country count twice in rankings and averages. forest.duplicated() flags rows that exactly repeat an earlier row, and .sum() counts them. The output np.int64(0) confirms none. For a table keyed by country, a stricter extra check is forest['iso3c'].is_unique, which would catch two different rows for the same code.

forest.duplicated().sum()
np.int64(0)

Part 5: Real World Aggregate Row#

Aggregate rows such as a world total must be separated from country rows, otherwise they distort averages and rankings. The code selects the row where iso3c is WLD and keeps it as a single record with .iloc[0]. It then keeps every other row as countries and uses reset_index(drop=True) to renumber them from 0 without keeping the old index as a column. The output (236, 4) confirms one row was removed.

world = forest[forest['iso3c'] == 'WLD'].iloc[0]
countries = forest[forest['iso3c'] != 'WLD'].reset_index(drop=True)
countries.shape
(236, 4)

Part 6: Real Global Forest Trend#

The world row gives the official global picture, which is the right headline figure. Selecting three fields from world shows forest cover fell from 31.9% of land area in 2000 to 31.2% in 2020, a trend of -2.2%. That is a drop of 0.7 percentage points. The difference between percent change and percentage points matters: a percentage point is the simple difference between two percentages, while percent change compares it with the starting value.

world[['forests_2000', 'forests_2020', 'trend']]
forests_2000    31.9
forests_2020    31.2
trend           -2.2
Name: 233, dtype: object

Part 7: Real Country-Level Averages#

A simple average of country values is a useful comparison with the world figure. The code takes .mean() of each year's column across the 236 countries and rounds to two decimals. The output (32.26, 31.59) shows the average country fell from 32.26% to 31.59%. This differs from the world figure because it treats a small island the same as a huge country; the world row is effectively weighted by land area.

avg_2000 = round(countries['forests_2000'].mean(), 2)
avg_2020 = round(countries['forests_2020'].mean(), 2)
avg_2000, avg_2020
(np.float64(32.26), np.float64(31.59))

Part 8: Real Forest Trend Distribution Chart#

A histogram shows how percent changes are spread across countries, revealing whether most changed a little or a lot. countries['trend'].dropna() removes the 10 missing values, which ax.hist cannot plot, and bins=25 splits the range into 25 equal-width bars. The chart is saved as trend_distribution.png with no inline output. In the image, expect a tall cluster near zero with long tails, including the extreme -100 and +86 values.

fig, ax = plt.subplots(figsize=(9, 6))
ax.hist(countries['trend'].dropna(), bins=25, color='seagreen', edgecolor='black')
ax.set_xlabel('Real Percent Change in Forest Share, 2000 to 2020')
ax.set_ylabel('Real Number of Countries')
ax.set_title('Real Distribution of Forest Change by Country')
plt.tight_layout()
plt.savefig('trend_distribution.png', dpi=100)
plt.close()

Part 9: Real Top Five Forest Gainers#

Ranking the biggest percent gainers highlights where forest cover grew fastest relative to where it started. The code drops rows with no trend, then nlargest(5, 'trend') returns the top five. The output is led by Guernsey (GGY) at 86.2%, then Bahrain at 80.0% and Iceland at 66.7%. Look at the starting values, though: Iceland went from just 0.3% to 0.5%, so a large percent change can reflect a very small real change.

top_gainers = countries.dropna(subset=['trend']).nlargest(5, 'trend')[['iso3c', 'forests_2000', 'forests_2020', 'trend']]
top_gainers
iso3c forests_2000 forests_2020 trend
87 GGY 2.9 5.4 86.2
15 BHR 0.5 0.9 80.0
95 ISL 0.3 0.5 66.7
57 DJI 0.2 0.3 50.0
226 URY 7.8 11.6 48.7

Part 10: Real Top Five Forest Losers#

The biggest percent losers are the mirror ranking. nsmallest(5, 'trend') returns the five most negative values after dropping missing ones. Egypt (EGY) shows -100%, from 0.1% to 0.0%, which is likely a rounding effect on a tiny value rather than total loss. The others are more substantial: Côte d'Ivoire (CIV) fell from 16.0% to 8.9% (-44.4%) and Nicaragua from 44.9% to 28.3% (-37.0%). Always check extreme values against the raw numbers before reporting them.

top_losers = countries.dropna(subset=['trend']).nsmallest(5, 'trend')[['iso3c', 'forests_2000', 'forests_2020', 'trend']]
top_losers
iso3c forests_2000 forests_2020 trend
61 EGY 0.1 0.0 -100.0
48 CIV 16.0 8.9 -44.4
148 NIC 44.9 28.3 -37.0
40 TCD 5.0 3.4 -32.0
76 GMB 35.3 24.0 -32.0

Part 11: Real Point Change Column#

Percentage-point change avoids the small-base problem, so it is a fairer way to compare countries with very different starting levels. The code subtracts forests_2000 from forests_2020 to create point_change. The output shows the first three rows: Afghanistan 0.0, Albania 0.7 and Algeria 0.1. Compare Algeria's 0.1 points with its 14.3% trend to see how different the two measures can look.

countries['point_change'] = countries['forests_2020'] - countries['forests_2000']
countries[['iso3c', 'forests_2000', 'forests_2020', 'point_change']].head(3)
iso3c forests_2000 forests_2020 point_change
0 AFG 1.9 1.9 0.0
1 ALB 28.1 28.8 0.7
2 DZA 0.7 0.8 0.1

Part 12: Real Top Five Point-Change Gainers#

Ranking by percentage points shows which countries added the most forest cover in real terms. nlargest(5, 'point_change') returns the top five. Montenegro (MNE) leads with a 15.0-point rise, from 46.5% to 61.5%, followed by Vietnam with 8.8 and Cuba with 8.5. None of these appeared in the percent ranking, which shows why it is worth checking both measures before drawing conclusions.

top_point_gainers = countries.nlargest(5, 'point_change')[['iso3c', 'forests_2000', 'forests_2020', 'point_change']]
top_point_gainers
iso3c forests_2000 forests_2020 point_change
137 MNE 46.5 61.5 15.0
230 VNM 37.9 46.7 8.8
50 CUB 22.7 31.2 8.5
167 PRI 48.4 56.0 7.6
85 GUM 44.4 51.9 7.5

Part 13: Real Most Forested Countries in 2020#

Knowing which countries are most forested gives context to the change figures. nlargest(10, 'forests_2020') returns the ten highest 2020 shares. Suriname (SUR) tops the list at 97.4%, followed by French Guiana at 96.6% and Guyana at 93.6%, with several small Pacific island territories such as Micronesia (FSM) and Palau also in the top ten. Papua New Guinea completes the list at 79.2%.

most_forested = countries.nlargest(10, 'forests_2020')[['iso3c', 'forests_2020']]
most_forested
iso3c forests_2020
202 SUR 97.4
73 GUF 96.6
90 GUY 93.6
134 FSM 92.0
75 GAB 91.3
194 SLB 90.1
158 PLW 90.0
63 GNQ 87.3
3 ASM 85.7
160 PNG 79.2

Part 14: Real Least Forested Countries in 2020#

The least forested places show the other end of the scale. The code first filters to forests_2020 > 0 so countries with no forest at all do not fill the list, then nsmallest(10, ...) returns the ten lowest. The output runs from the Faroe Islands and Libya at 0.1% to Bahrain at 0.9%, mostly desert or treeless island areas. Excluding zeros is a deliberate choice: state it when you share a ranking like this.

least_forested = countries[countries['forests_2020'] > 0].nsmallest(10, 'forests_2020')[['iso3c', 'forests_2020']]
least_forested
iso3c forests_2020
69 FRO 0.1
118 LBY 0.1
51 CUW 0.2
57 DJI 0.3
130 MRT 0.3
111 KWT 0.4
95 ISL 0.5
185 SAU 0.5
2 DZA 0.8
15 BHR 0.9

Part 15: Real Zero-Forest Country Count#

The zero-forest countries were left out of the previous ranking, so it is important to count them separately. (countries['forests_2020'] == 0).sum() counts places with no recorded forest in 2020. The output is 11. These rows help explain why trend is missing for 10 countries: if the share was zero in 2000 too, a percent change cannot be calculated.

zero_forest_count = (countries['forests_2020'] == 0).sum()
zero_forest_count
np.int64(11)

Part 16: Real Gain vs Loss vs Stable Split#

Counting how many countries moved in each direction shows whether forest loss is widespread or concentrated. Each line compares trend with zero and counts the Trues. The output (87, 94, 45) shows 87 gaining, 94 losing and 45 unchanged. Together that is 226, which is 10 short of 236 because missing trend values are neither above, below nor equal to zero in pandas comparisons, so they are not counted in any group.

gaining = (countries['trend'] > 0).sum()
losing = (countries['trend'] < 0).sum()
stable = (countries['trend'] == 0).sum()
gaining, losing, stable
(np.int64(87), np.int64(94), np.int64(45))

Part 17: Real Gain vs Loss Chart#

A three-bar chart makes the gain, loss and stable split easy to grasp. ax.bar takes a list of three labels and the three counts, with green, red and blue colours. The chart is saved as gain_vs_loss.png with no inline output. In the image, the gaining and losing bars should be close in height (87 and 94), so the world-level decline is not simply a story of most countries losing forest; how much land each country has also matters.

fig, ax = plt.subplots(figsize=(7, 6))
ax.bar(['Real Gaining', 'Real Losing', 'Real Stable'], [gaining, losing, stable], color=['seagreen', 'firebrick', 'steelblue'])
ax.set_ylabel('Real Number of Countries')
ax.set_title('Real Countries Gaining vs Losing Forest, 2000-2020')
plt.tight_layout()
plt.savefig('gain_vs_loss.png', dpi=100)
plt.close()

Part 18: Real 2000 vs 2020 Scatter Chart#

A scatter chart of 2000 against 2020 shows every country's change in one view. ax.scatter plots each country's 2000 share on the x-axis and 2020 share on the y-axis, and ax.plot([0, 100], [0, 100], linestyle='--') adds a dashed diagonal reference line where the two years are equal. The chart is saved as forest_2000_vs_2020.png. In the image, points above the line gained forest, points below lost it, and the distance from the line shows how big the change was.

fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(countries['forests_2000'], countries['forests_2020'], alpha=0.5, color='darkorange')
ax.plot([0, 100], [0, 100], color='gray', linestyle='--', linewidth=1)
ax.set_xlabel('Real Forest Share 2000, Percent')
ax.set_ylabel('Real Forest Share 2020, Percent')
ax.set_title('Real Forest Share, 2000 vs 2020')
plt.tight_layout()
plt.savefig('forest_2000_vs_2020.png', dpi=100)
plt.close()

Part 19: Real 2000-to-2020 Correlation#

Correlation measures how closely two sets of values move together, from -1 to 1. countries['forests_2000'].corr(countries['forests_2020']) calculates it across all countries and rounds to four decimals. The output is 0.989, which is extremely high: countries that were heavily forested in 2000 were almost all still heavily forested in 2020. That is expected over 20 years, and it means the interesting story lies in the smaller deviations from the diagonal.

corr_2000_2020 = round(countries['forests_2000'].corr(countries['forests_2020']), 4)
corr_2000_2020
np.float64(0.989)

Part 20: Real Severity Classification#

Grouping countries into severity bands turns a raw number into categories a report reader can act on. np.select checks a list of conditions in order and assigns the matching label: missing trend first, then gaining, a loss of under 10%, a loss of 10 to 25%, and a loss of 25% or more. The output shows 101 stable or mild loss, 87 gaining, 27 moderate loss, 11 severe loss and 10 no data. Putting the isna() check first ensures missing values get their own label.

conditions = [countries['trend'].isna(), countries['trend'] > 0, (countries['trend'] <= 0) & (countries['trend'] > -10), (countries['trend'] <= -10) & (countries['trend'] > -25), countries['trend'] <= -25]
choices = ['no_data', 'gaining', 'stable_or_mild_loss', 'moderate_loss', 'severe_loss']
countries['severity'] = np.select(conditions, choices, default='no_data')
countries['severity'].value_counts()
severity
stable_or_mild_loss    101
gaining                 87
moderate_loss           27
severe_loss             11
no_data                 10
Name: count, dtype: int64

Part 21: Real Severity Category Chart#

A bar chart of the severity bands shows how the countries are distributed at a glance. The code plots value_counts() of severity with kind='bar' and uses plt.xticks(rotation=30, ha='right') to tilt the longer labels so they do not overlap, aligning each to the right of its bar. The chart is saved as severity_categories.png with no inline output. In the image, the bars run from largest to smallest, with stable or mild loss tallest.

fig, ax = plt.subplots(figsize=(9, 6))
countries['severity'].value_counts().plot(kind='bar', ax=ax, color='indianred')
ax.set_xlabel('Real Severity Category')
ax.set_ylabel('Real Number of Countries')
ax.set_title('Real Countries by Forest Loss Severity')
plt.xticks(rotation=30, ha='right')
plt.tight_layout()
plt.savefig('severity_categories.png', dpi=100)
plt.close()

Part 22: Real Severe Loss Count#

The severe-loss group is the one policy makers would focus on, so it helps to express it as a share. The code counts rows labelled severe_loss and divides by len(countries), then multiplies by 100. The output (11, 4.7) shows 11 countries, 4.7% of the 236. Note the denominator includes the 10 no-data rows; dividing by only the 226 countries with a trend value would give a slightly higher share.

severe_count = (countries['severity'] == 'severe_loss').sum()
severe_pct = round(severe_count / len(countries) * 100, 1)
severe_count, severe_pct
(np.int64(11), np.float64(4.7))

Part 23: Real Average Forest Share by Severity#

Comparing the 2020 forest share across severity groups shows whether heavy losses happen mainly in less forested places. groupby('severity')['forests_2020'].mean() averages each group. The output shows severe-loss countries averaged 17.45% forest cover, compared with 37.29% for stable or mild loss and 31.21% for gaining. The no-data group averages 0.00, consistent with those being places with no forest at all.

severity_avg = countries.groupby('severity')['forests_2020'] .mean().round(2)
severity_avg
severity
gaining                31.21
moderate_loss          28.94
no_data                 0.00
severe_loss            17.45
stable_or_mild_loss    37.29
Name: forests_2020, dtype: float64

Part 24: Real Most-Forested Countries Trend#

The most forested countries hold much of the world's forest, so their trend matters a lot. nlargest(10, 'forests_2020') selects the ten most forested, and the code averages their trend values. The output is -0.94, meaning these countries lost just under 1% of their forest share on average. That is a small relative loss, but on a very large forest base it can still represent a lot of forest.

top10_forested = countries.nlargest(10, 'forests_2020')
round(top10_forested['trend'].mean(), 2)
np.float64(-0.94)

Part 25: Real Sanity Check, World vs Country Average#

This check confirms that two independent views of the data point the same way. The expression tests whether the world trend is negative and the country average for 2020 is below 2000, joined with and so both must be true. The output np.True_ (numpy's True) confirms both measures show decline. If the two had disagreed, it would be a signal to look more closely at how the world figure is calculated.

world['trend'] < 0 and avg_2020 < avg_2000
np.True_

Part 26: Saving the Real Enriched Dataset#

Saving the enriched country table keeps point_change and severity for later work. to_csv(..., index=False) writes the file without the index, and the code reloads it and compares shapes. The output is True, so nothing was lost. Notice the saved file excludes the world row, which is usually what you want for country-level analysis.

countries.to_csv('forest_shares_enriched.csv', index=False)
reloaded = pd.read_csv('forest_shares_enriched.csv')
reloaded.shape == countries.shape
True

Part 27: Real Sanity Check, Row Count#

This check confirms that adding columns has not changed the number of countries. len(countries) == 236 compares the row count with the expected value after removing the world row. The output is True. Writing the expected number into the check makes it obvious if an earlier filter is accidentally changed.

len(countries) == 236
True

Part 28: Real Sanity Check, No Missing Core Columns#

The core forest share columns feed every ranking and average, so they must be complete. The code counts NaN in forests_2000 and forests_2020 with .isna().sum(), adds the two counts with a second .sum(), and checks the total is zero. The output np.True_ confirms no gaps. Only trend has missing values, and those were labelled no_data rather than dropped.

countries[['forests_2000', 'forests_2020']].isna().sum().sum() == 0
np.True_

Part 29: Real Top Finding Print#

The top finding is turned into a sentence for a report. The code takes the first row of top_gainers with .iloc[0] and inserts its code, both shares and trend into an f-string. The output reports Guernsey (GGY) as the fastest percent gainer, rising from 2.9% to 5.4% forest cover, an 86.2% increase. When you share this, add the percentage-point change too, so readers see that the real rise was 2.5 points.

top_country = top_gainers.iloc[0]
print(f'The real fastest forest gainer by percent was {top_country["iso3c"]}, rising from {top_country["forests_2000"]} to {top_country["forests_2020"]} percent forest cover, a real {top_country["trend"]} percent increase.')
The real fastest forest gainer by percent was GGY, rising from 2.9 to 5.4 percent forest cover, a real 86.2 percent increase.

Part 30: Real Recap Print#

The recap brings together the country split and the world trend. The f-string uses len(countries), gaining, losing and the world row's values. The output reports 236 countries and territories, 87 gaining and 94 losing forest, and a world decline from 31.9% to 31.2%, a -2.2% change. The phrase 'a -2.2 percent decline' is a double negative in plain English, so when writing up findings by hand, say 'a 2.2% decline' instead.

print(f'Across {len(countries)} real countries and territories, {gaining} gained forest, {losing} lost forest, and the real world aggregate fell from {world["forests_2000"]} to {world["forests_2020"]} percent forest cover, a real {world["trend"]} percent decline.')
Across 236 real countries and territories, 87 gained forest, 94 lost forest, and the real world aggregate fell from 31.9 to 31.2 percent forest cover, a real -2.2 percent decline.

Wrap-Up: What You Learned#

  • This real lesson analyzed a real two hundred thirty-seven row forest cover dataset spanning real individual countries, real territories, and one real world aggregate row, comparing the real year 2000 to the real year 2020.
  • Real forest share fell for the real world overall, from 31.9 to 31.2 percent, even though nearly as many real countries gained forest as lost it.
  • Guernsey posted the real largest percent increase and Montenegro the real largest raw percentage-point increase, while Paraguay, Nicaragua, and the Northern Mariana Islands posted the real steepest raw percentage-point declines.
  • Splitting real countries into gaining, stable-or-mild-loss, moderate-loss, and severe-loss categories turned one raw trend number into something genuinely interpretable about the real scale of forest change.
  • Next video: a real global renewable energy dataset, moving this domain from real land cover into real energy production.

Practice on your own

  • Rank the five biggest losers by point_change with nsmallest(5, 'point_change') and compare the list with the percent-change losers.
  • Find the countries whose trend is missing and check their forests_2000 and forests_2020 values to confirm why no percent change was calculated.
  • Redo the severity bands using point_change instead of trend (for example, a loss of more than 5 points as severe) and compare the counts in each band.

The next lesson moves this domain from land cover into energy production with a global renewable energy dataset. Watch the video walkthrough of this lesson to see each step explained in action.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.