Mathew K Analytics

Lesson 52 · Real-World Data Analytics

Year-on-Year Growth with groupby & diff: Mauna Loa CO2 | Python Data Analytics #52

Moving from local weather to a real worldwide climate perspective. A real NOAA and Scripps Institution of Oceanography dataset of eight hundred eighteen…

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 52: Real Mauna Loa CO2 Record Analysis#

  • Video fifty-two of the hundred-video real-world data analytics series, moving from local weather to a real worldwide climate perspective.
  • A real NOAA and Scripps Institution of Oceanography dataset of eight hundred eighteen real monthly atmospheric CO2 measurements from the Mauna Loa Observatory, spanning March 1958 through April 2026.
  • Let's get into it.

This lesson is for learners who want to work with a long-running time series and learn how to separate a trend from a seasonal pattern. The question it answers is one that policy makers, journalists and climate analysts ask constantly: how much has atmospheric carbon dioxide (CO2) risen, and is the rise speeding up?

The data is the Keeling Curve, published by NOAA and the Scripps Institution of Oceanography from measurements at the Mauna Loa Observatory in Hawaii. It holds monthly readings from March 1958 to April 2026. The key columns are date (year and month as text), decimal_date, average (the monthly mean CO2 in parts per million, or ppm), interpolated, and ndays, the number of days with valid measurements.

In this lesson you will:

  • spot sentinel values, placeholder numbers such as -1 that stand in for missing data
  • extract years and calendar months from text dates
  • compute annual averages, year-on-year changes and a 12-month rolling average
  • measure the seasonal cycle and compare growth rates across decades

Prerequisites: you should be comfortable with pandas filtering and groupby. Earlier lessons in the series cover both if you need a refresher.

Part 1: The Real Keeling Curve#

Loading the file and checking its size confirms you have the full record before you analyse it. The code imports pandas, numpy and matplotlib, reads co2_mm_mlo.csv with pd.read_csv, and shows .shape. The output is (818, 7): 818 monthly readings across 7 columns. That count matches roughly 68 years of monthly data from 1958 to 2026, which is the famous Keeling Curve, the longest continuous direct record of atmospheric CO2.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
co2 = pd.read_csv('co2_mm_mlo.csv')
co2.shape
(818, 7)

Part 2: Real Data Preview#

A preview shows you how values are stored and warns you about anything unusual. The code has two expressions, but Jupyter only displays the last one, so you see co2.head(5) rather than the column list. Notice date is text such as 1958-03, average is CO2 in ppm (315.71 in the first month), and the early rows show ndays of -1, stdev_days of -9.99 and unc_mon_mean of -0.99. Those negative values are not real measurements: they are codes meaning the figure was not recorded.

co2.columns.tolist()
co2.head(5)
date decimal_date average interpolated ndays stdev_days unc_mon_mean
0 1958-03 1958.2027 315.71 314.44 -1 -9.99 -0.99
1 1958-04 1958.2877 317.45 315.16 -1 -9.99 -0.99
2 1958-05 1958.3699 317.51 314.69 -1 -9.99 -0.99
3 1958-06 1958.4548 317.27 315.15 -1 -9.99 -0.99
4 1958-07 1958.5370 315.87 315.20 -1 -9.99 -0.99

Part 3: Real Missing Data Check#

Missing values are the first thing to check, but this step also teaches an important lesson about what counts as missing. co2.isna().sum() counts empty cells per column, and the output shows 0 for all 7 columns. That looks perfectly clean, yet you already saw -1 and -9.99 in the preview. Pandas only treats truly empty cells (NaN) as missing, so codes like these slip straight past isna(). Always read the data documentation as well as running this check.

co2.isna().sum()
date            0
decimal_date    0
average         0
interpolated    0
ndays           0
stdev_days      0
unc_mon_mean    0
dtype: int64

Part 4: Real Duplicate Row Check#

Duplicate months would distort annual averages and growth rates, so you confirm there are none. co2.duplicated() flags rows that exactly repeat an earlier row, and .sum() counts them. The output np.int64(0) means there are no duplicates. For time series, a stricter extra check is to look for repeated values in the date column alone, since two different readings for the same month would not be caught here.

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

Part 5: Real Sentinel Value Count#

A sentinel value is a placeholder number used instead of a blank, and you need to know how widespread they are before you trust a column. The code compares ndays with -1 and counts the Trues with .sum(). The output is 195, meaning 195 months have no recorded count of measurement days, mostly from the early decades. The average column itself is still usable, but if you ever analyse ndays or stdev_days, replace these codes with NaN first, for example using .replace(-1, np.nan).

sentinel_rows = (co2['ndays'] == -1).sum()
sentinel_rows
np.int64(195)

Part 6: Real First and Latest Reading#

The first and latest readings frame the whole story. co2.iloc[0] selects the first row by position and co2.iloc[-1] the last, and the code returns the date and average from each as a pair. The output shows 315.71 ppm in 1958-03 and 431.12 ppm in 2026-04, at row positions 0 and 817. Using iloc with -1 is a handy way to grab the final row without knowing how long the data is.

first_reading = co2.iloc[0]
last_reading = co2.iloc[-1]
first_reading[['date', 'average']], last_reading[['date', 'average']]
(date       1958-03
 average     315.71
 Name: 0, dtype: object,
 date       2026-04
 average     431.12
 Name: 817, dtype: object)

Part 7: Real Total Increase#

A single headline number is often what stakeholders remember, so the next step calculates the absolute rise. The code subtracts the first monthly average from the latest and rounds to two decimals. The output is 115.41, so CO2 has increased by 115.41 ppm over the record. Bear in mind that comparing single months mixes in seasonal effects: March and April are both high-season months, so the comparison is reasonably fair here.

total_increase = round(last_reading['average'] - first_reading['average'], 2)
total_increase
np.float64(115.41)

Part 8: Real Percent Increase#

An absolute change is easier to interpret alongside a relative one. The code divides total_increase by the first reading, multiplies by 100 and rounds to one decimal place. The output is 36.6, meaning atmospheric CO2 is 36.6% higher than in March 1958. Always state which baseline you divided by, because using the latest value instead of the first would give a different percentage.

pct_increase = round(total_increase / first_reading['average'] * 100, 1)
pct_increase
np.float64(36.6)

Part 9: Real Year Extraction#

To summarise by year you first need a numeric year column. Because date is text in the form YYYY-MM, .str.slice(0, 4) takes the first four characters, and .astype(int) converts them to whole numbers. The output (1958, 2026) confirms the earliest and latest years. Slicing text is quick here because the format is consistent; for messier dates, pd.to_datetime would be the safer choice.

co2['year'] = co2['date'].str.slice(0, 4).astype(int)
co2['year'].min(), co2['year'].max()
(np.int64(1958), np.int64(2026))

Part 10: Real Annual Average CO2#

Annual averages smooth out the monthly ups and downs so you can see the long-term trend. groupby('year')['average'].mean() averages all months within each year, and .tail(10).round(2) shows the last ten years. The output climbs every year, from 406.76 ppm in 2017 to 427.35 ppm in 2025. Be careful with 2026: its 429.81 is based on only a few early months, so it is not a full-year average and should not be compared directly.

annual_avg = co2.groupby('year')['average'].mean()
annual_avg.tail(10).round(2)
year
2017    406.76
2018    408.72
2019    411.65
2020    414.21
2021    416.41
2022    418.53
2023    421.08
2024    424.60
2025    427.35
2026    429.81
Name: average, dtype: float64

Part 11: Real Full-History Chart#

Plotting every monthly reading reveals both the steady rise and the regular wiggle of the seasons. The code draws a single line with ax.plot, using range(len(co2)) as the x-axis so each point is simply a month number counted from March 1958. The chart is saved as co2_full_history.png and closed, so there is no inline output. When you open it, look for the upward curve that gets steeper over time and the small saw-tooth pattern that repeats each year.

fig, ax = plt.subplots(figsize=(11, 6))
ax.plot(range(len(co2)), co2['average'], color='firebrick', linewidth=0.8)
ax.set_xlabel('Real Months Since March 1958')
ax.set_ylabel('Real CO2, Parts Per Million')
ax.set_title('Real Mauna Loa Monthly CO2, 1958-2026')
plt.tight_layout()
plt.savefig('co2_full_history.png', dpi=100)
plt.close()

Part 12: Real Decade Comparison#

Comparing whole decades is a robust way to show change, because averaging ten years irons out single unusual months. Each line filters rows with two conditions joined by & (each wrapped in brackets) and takes the mean of average. The output is (320.29, 415.37): the 1960s averaged 320.29 ppm, while 2016 to 2025 averaged 415.37 ppm, a gap of about 95 ppm. Notice the recent window is chosen to use only complete years.

decade_1960s = co2[(co2['year'] >= 1960) & (co2['year'] <= 1969)]['average'].mean()
decade_2016_2025 = co2[(co2['year'] >= 2016) & (co2['year'] <= 2025)]['average'].mean()
round(decade_1960s, 2), round(decade_2016_2025, 2)
(np.float64(320.29), np.float64(415.37))

Part 13: Real First Month Above 400 PPM#

Round-number thresholds such as 400 ppm are milestones that make news, so it is worth finding when the line was first crossed. The code filters to months where average >= 400, and .iloc[0] takes the first matching row, which is the earliest because the data is in date order. The output shows 2013-05 at 400.02 ppm. This relies on the rows being sorted by date, which a later sanity check confirms.

above_400 = co2[co2['average'] >= 400]
above_400.iloc[0][['date', 'average']]
date       2013-05
average     400.02
Name: 662, dtype: object

Part 14: Real Months Above 400 PPM#

Once you know when the threshold was first crossed, the next question is how persistent it has been. len(above_400) counts the rows in the filtered table. The output is 137, so 137 monthly readings have been at or above 400 ppm. There are 156 months from May 2013 to April 2026 inclusive, so 19 months after 2013 still dipped below 400, which is the seasonal cycle at work before the trend pulled every month above the line.

months_above_400 = len(above_400)
months_above_400
137

Part 15: Real Fastest Annual Increase#

Growth rate matters as much as level: an accelerating rise is a stronger signal than a steady one. The code first drops the incomplete final year by keeping only years below the maximum, then .diff() subtracts each year's average from the next. Sorting in descending order shows the largest jumps: 3.53 ppm in 2024, 3.40 ppm in 2016 and 2.96 ppm in 1998. Excluding the partial year is essential, since a four-month average would give a misleading change.

complete_years = annual_avg[annual_avg.index < co2['year'].max()]
annual_diff = complete_years.diff()
annual_diff.sort_values(ascending=False).head(3).round(2)
year
2024    3.53
2016    3.40
1998    2.96
Name: average, dtype: float64

Part 16: Real Annual Trend Chart#

A chart of annual averages shows the trend without the seasonal noise. The code calls .plot() directly on the complete_years Series, which uses the year index as the x-axis, with a thick dark green line. The figure is saved as co2_annual_trend.png and closed, so nothing appears inline. In the image, look at the slope: it should get steeper from left to right, which is what acceleration looks like on a line chart.

fig, ax = plt.subplots(figsize=(9, 6))
complete_years.plot(ax=ax, color='darkgreen', linewidth=2)
ax.set_xlabel('Real Year')
ax.set_ylabel('Real Annual Average CO2, PPM')
ax.set_title('Real Annual Average Mauna Loa CO2, 1958-2025')
plt.tight_layout()
plt.savefig('co2_annual_trend.png', dpi=100)
plt.close()

Part 17: Real Seasonal Cycle#

CO2 rises and falls within each year as Northern Hemisphere plants absorb carbon in summer and release it in autumn and winter. The code takes characters 5 to 7 of date with .str.slice(5, 7) to get the calendar month, then averages average by that month. The output peaks at 363.80 ppm in month 4, April, and bottoms out at 357.75 ppm in month 9, September. Because the trend is mixed in and not every month appears in every year, treat these as a rough picture of the cycle.

co2['cal_month'] = co2['date'].str.slice(5, 7).astype(int)
seasonal_cycle = co2.groupby('cal_month')['average'].mean().round(2)
seasonal_cycle
cal_month
1     361.57
2     362.35
3     362.51
4     363.80
5     363.39
6     362.84
7     361.30
8     359.28
9     357.75
10    357.81
11    359.16
12    360.48
Name: average, dtype: float64

Part 18: Real Seasonal Cycle Chart#

A bar per calendar month makes the seasonal cycle easy to see. The code plots seasonal_cycle with kind='bar', keeps the month labels upright with plt.xticks(rotation=0), and saves the chart as co2_seasonal_cycle.png without showing it inline. When you look at the image, the bars will look similar in height because the y-axis starts near zero; the difference between months is only a few ppm. Setting a tighter y-axis range with ax.set_ylim would make the cycle stand out more.

fig, ax = plt.subplots(figsize=(9, 6))
seasonal_cycle.plot(kind='bar', ax=ax, color='teal')
ax.set_xlabel('Real Calendar Month')
ax.set_ylabel('Real Average CO2, PPM')
ax.set_title('Real Seasonal CO2 Cycle, Averaged Across 1958-2026')
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig('co2_seasonal_cycle.png', dpi=100)
plt.close()

Part 19: Real Seasonal Amplitude#

Amplitude is the distance between the high and low point of a cycle, a simple way to measure how strong the seasonal swing is. The code subtracts the minimum of seasonal_cycle from its maximum and also returns which months they occur in with idxmax() and idxmin(). The output (4, 9, 6.05) shows the peak in April, the trough in September and an amplitude of about 6.05 ppm. This is small next to the 115 ppm long-term rise, which shows the trend dominates.

seasonal_amplitude = round(seasonal_cycle.max() - seasonal_cycle.min(), 2)
seasonal_cycle.idxmax(), seasonal_cycle.idxmin(), seasonal_amplitude
(np.int64(4), np.int64(9), np.float64(6.05))

Part 20: Real 12-Month Rolling Average#

A rolling average replaces each value with the mean of a moving window, which smooths out short-term swings. .rolling(12).mean() averages each month with the previous eleven, so every point covers a full seasonal cycle. The first eleven rows become NaN because there is not yet a full window. The output's last row shows April 2026 at 431.12 ppm raw but 427.99 ppm smoothed, so the latest reading sits above the yearly average because spring is the seasonal peak.

co2['rolling_12mo'] = co2['average'].rolling(12).mean()
co2[['date', 'average', 'rolling_12mo']].tail(5)
date average rolling_12mo
813 2025-12 427.49 427.349167
814 2026-01 428.62 427.513333
815 2026-02 429.35 427.701667
816 2026-03 430.15 427.868333
817 2026-04 431.12 427.991667

Part 21: Real Raw vs Rolling Average Chart#

Overlaying the raw and smoothed lines shows clearly what the rolling average removes. The code plots the monthly readings as a thin light line and the 12-month rolling average as a thick dark red line on the same axes, adds a legend, and saves the figure as co2_rolling_average.png. There is no inline output. In the image, the smooth line should run through the middle of the seasonal wiggles, starting a year later than the raw line because of the initial NaN values.

fig, ax = plt.subplots(figsize=(11, 6))
ax.plot(range(len(co2)), co2['average'], color='lightcoral', linewidth=0.6, label='Real Monthly Reading')
ax.plot(range(len(co2)), co2['rolling_12mo'], color='darkred', linewidth=2, label='Real 12-Month Rolling Average')
ax.set_xlabel('Real Months Since March 1958')
ax.set_ylabel('Real CO2, Parts Per Million')
ax.set_title('Real Mauna Loa CO2, Raw Readings vs Real Smoothed Trend')
ax.legend()
plt.tight_layout()
plt.savefig('co2_rolling_average.png', dpi=100)
plt.close()

Part 22: Real Growth Rate Acceleration#

To test whether CO2 is rising faster now than in the past, you compare the average yearly increase in two decades. complete_years.loc[1960:1969] selects years by label (and includes both ends), .diff() gives the year-on-year changes and .mean() averages them. The output (0.86, 2.55) shows CO2 rose about 0.86 ppm per year in the 1960s against 2.55 ppm per year in 2016 to 2025, roughly three times faster. That is clear evidence of acceleration.

early_growth = complete_years.loc[1960:1969].diff().mean()
recent_growth = complete_years.loc[2016:2025].diff().mean()
round(early_growth, 2), round(recent_growth, 2)
(np.float64(0.86), np.float64(2.55))

Part 23: Real Partial Final Year#

Partial periods are a common trap in time series work, so it pays to count exactly how much of the final year you have. The code compares year with the latest year and counts the matches. The output is 4, so 2026 contains only January to April. This is why the earlier growth calculations excluded 2026: a four-month average leans towards the spring peak and would make the year look higher than a full year would.

final_year_months = (co2['year'] == co2['year'].max()).sum()
final_year_months
np.int64(4)

Part 24: Real Recent 12-Month Average#

The latest twelve months give a fair, up-to-date level that includes one of every calendar month. co2['average'].tail(12) takes the last twelve rows and .mean() averages them. The output is 427.99 ppm, which matches the final value of the rolling average, as it should. Reporting a 12-month figure is a good habit whenever your data has a strong seasonal pattern.

recent_12mo_avg = round(co2['average'].tail(12).mean(), 2)
recent_12mo_avg
np.float64(427.99)

Part 25: Real Enriched Dataset#

A flag column makes a key threshold easy to filter on later. co2['average'] >= 400 creates a True or False column called above_400ppm, and .sum() counts the True values. The output is 137, the same as the earlier count of months above 400 ppm, which confirms the flag is consistent. Flags like this are useful in dashboards, where users can filter or colour by them.

co2['above_400ppm'] = co2['average'] >= 400
co2['above_400ppm'].sum()
np.int64(137)

Part 26: Saving the Real Enriched Dataset#

Saving the enriched data lets you or a colleague pick up from here without repeating the work. to_csv(..., index=False) writes the file without the pandas index, and the code reloads it and compares the shape with the original. The output is True, so the rows and columns survived the round trip. Remember that the NaN values in rolling_12mo will be written as empty cells, which is the correct way to store them.

co2.to_csv('co2_mlo_enriched.csv', index=False)
reloaded = pd.read_csv('co2_mlo_enriched.csv')
reloaded.shape == co2.shape
True

Part 27: Real Sanity Check, Total Months#

A quick test confirms that no rows were lost or added during the analysis. len(co2) == 818 compares the current row count with the original. The output is True, so the dataset still holds every monthly reading. It is easy to overwrite a DataFrame with a filtered version by accident, and checks like this catch that before you report results.

len(co2) == 818
True

Part 28: Real Sanity Check, Monotonic Dates#

Several steps assumed the rows were in time order, such as taking the first month above 400 ppm and computing the rolling average. .is_monotonic_increasing returns True if every value in decimal_date is greater than or equal to the one before. The output is True, so the data is sorted correctly. If it returned False, you would sort with sort_values('decimal_date') before any time-based calculation.

co2['decimal_date'].is_monotonic_increasing
True

Part 29: Real Top Finding Print#

The headline finding is turned into one clear sentence that could open a report. The f-string pulls the first and latest readings, the absolute increase and the percentage into the text. The output states that CO2 rose from 315.71 ppm in 1958-03 to 431.12 ppm in 2026-04, an increase of 115.41 ppm or 36.6 percent. Building text from variables keeps the sentence correct automatically when new monthly data is added.

print(f'Atmospheric CO2 has genuinely risen from {first_reading["average"]} ppm in {first_reading["date"]} to {last_reading["average"]} ppm in {last_reading["date"]}, a real increase of {total_increase} ppm, or {pct_increase} percent.')
Atmospheric CO2 has genuinely risen from 315.71 ppm in 1958-03 to 431.12 ppm in 2026-04, a real increase of 115.41 ppm, or 36.6 percent.

Part 30: Real Recap Print#

The recap brings together the threshold, the current level and the acceleration in a single sentence. The f-string uses len(co2), the first date from above_400, recent_12mo_avg and both growth rates, rounded inside the string. The output reports 818 readings, a first crossing of 400 ppm in 2013-05, a recent 12-month average of 427.99 ppm, and growth of 2.55 ppm per year in 2016 to 2025 versus 0.86 in the 1960s. Pairing a level with a rate gives readers both where we are and how fast it is changing.

print(f'Across {len(co2)} real monthly readings, CO2 first crossed 400 ppm in {above_400.iloc[0]["date"]}, now sits at a real recent twelve-month average of {recent_12mo_avg} ppm, and rose {round(recent_growth,2)} ppm per year on average in 2016-2025, versus {round(early_growth,2)} ppm per year in the 1960s.')
Across 818 real monthly readings, CO2 first crossed 400 ppm in 2013-05, now sits at a real recent twelve-month average of 427.99 ppm, and rose 2.55 ppm per year on average in 2016-2025, versus 0.86 ppm per year in the 1960s.

Wrap-Up: What You Learned#

  • This real lesson used the Keeling Curve, a real NOAA and Scripps dataset of eight hundred eighteen real monthly CO2 readings from Mauna Loa, Hawaii, spanning March 1958 through April 2026.
  • Real atmospheric CO2 has risen from 315.71 to 431.12 parts per million, a genuine thirty-six point six percent increase, and first crossed the real four-hundred-ppm threshold in May 2013.
  • A real recurring seasonal cycle, driven by Northern Hemisphere plant growth, adds and removes about six parts per million every real year, on top of the long-term real upward trend.
  • Real CO2 is genuinely rising faster now than it did in the 1960s, and this dataset's honest final year was left as a real partial four-month sample rather than treated as a complete year.
  • Next video: a real global sea level rise dataset, continuing this domain's worldwide climate perspective.

Practice on your own

  • Replace the -1 codes in ndays with NaN using .replace(-1, np.nan), then find the first year in which every month has a valid ndays value.
  • Compute the seasonal amplitude separately for each complete year (max minus min of average within the year) and check whether the swing has grown since the 1960s.
  • Calculate the year-on-year change for each month by comparing it with the same month twelve rows earlier using .diff(12), then find the month with the largest jump.

The next lesson continues the worldwide climate theme with a global sea level rise 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.