Mathew K Analytics

Lesson 53 · Real-World Data Analytics

Fit a Trend Line with NumPy: Sea Level Rise Data Analysis | Python Data Analytics #53

Continuing this domain's worldwide climate perspective. A real dataset combining two independent government sources, real CSIRO tide-gauge records from 1880…

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 53: Real Global Sea Level Rise Analysis#

  • Video fifty-three of the hundred-video real-world data analytics series, continuing this domain's worldwide climate perspective.
  • A real dataset combining two independent government sources, real CSIRO tide-gauge records from 1880 to 2013 and real NOAA satellite records from 1993 to 2023, both measuring real global mean sea level.
  • Let's get into it.

This lesson is for learners ready to combine two data sources that measure the same thing in different ways, a situation analysts meet constantly. The question is: how much has global sea level risen since 1880, and is it rising faster in recent decades?

The dataset joins two independent government records of global mean sea level, measured in inches. CSIRO tide-gauge readings run from 1880 to 2013 and include lower and upper error bounds, which show how uncertain each estimate is. NOAA satellite readings run from 1993 to 2023. Each row is one year, and each source leaves blanks for years it did not cover.

In this lesson you will:

  • explain missing values that come from coverage gaps rather than errors
  • compare two sources over the years they overlap, using correlation and average difference
  • fit straight-line trends with np.polyfit and compare rates of rise
  • track how measurement uncertainty changed over time
  • merge two series into one best estimate with combine_first

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

Part 1: Two Real Sea Level Sources#

Loading the data and checking its shape tells you whether the file covers the period you expect. The code imports pandas, numpy and matplotlib, reads epa_sea_level.csv and shows .shape. The output is (144, 5): 144 rows, one per year from 1880 to 2023, and 5 columns. Because two sources with different time spans share this table, expect many blank cells, which the next steps investigate.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
sea = pd.read_csv('epa_sea_level.csv')
sea.shape
(144, 5)

Part 2: Real Data Preview#

Previewing the first rows shows column names, units and how missing data appears. The code contains two expressions, but Jupyter only displays the last, so you see sea.head(3). The CSIRO column starts at 0.000000 in 1880, which tells you the values are changes relative to that starting year rather than absolute heights. The error bounds sit either side of each estimate, and the NOAA column shows NaN, pandas' marker for a missing value, because satellites did not exist in the 1880s.

sea.columns.tolist()
sea.head(3)
Year CSIRO Adjusted Sea Level Lower Error Bound Upper Error Bound NOAA Adjusted Sea Level
0 1880 0.000000 -0.952756 0.952756 NaN
1 1881 0.220472 -0.732283 1.173228 NaN
2 1882 -0.440945 -1.346457 0.464567 NaN

Part 3: Real Missing Data Check#

Counting missing values tells you how complete each column is and, here, hints at why. sea.isna().sum() counts NaN cells per column. The output shows 0 missing years, 10 missing values in each of the three CSIRO columns and 113 missing in NOAA. These gaps are expected: CSIRO ends in 2013, leaving 10 later years blank, and NOAA starts in 1993, leaving 113 earlier years blank. Missing data is not always an error; sometimes it reflects when something was measured.

sea.isna().sum()
Year                          0
CSIRO Adjusted Sea Level     10
Lower Error Bound            10
Upper Error Bound            10
NOAA Adjusted Sea Level     113
dtype: int64

Part 4: Real Duplicate Row Check#

Duplicate rows would double-count years and skew averages and trends. sea.duplicated() flags any row identical to an earlier one, and .sum() counts the flags. The output np.int64(0) shows there are no duplicates. A later sanity check also confirms each year appears only once, which is the stricter test for time series data.

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

Part 5: Real Column Rename#

Long column names with spaces, such as CSIRO Adjusted Sea Level, are awkward to type and easy to misspell. Assigning a new list to sea.columns renames all five columns at once, in order, to year, csiro, csiro_lower, csiro_upper and noaa. The output shows the same three rows with the new short names. This approach depends on the list matching the original column order exactly, so check the preview before relying on it; rename() with a dictionary is safer when order is uncertain.

sea.columns = ['year', 'csiro', 'csiro_lower', 'csiro_upper', 'noaa']
sea.head(3)
year csiro csiro_lower csiro_upper noaa
0 1880 0.000000 -0.952756 0.952756 NaN
1 1881 0.220472 -0.732283 1.173228 NaN
2 1882 -0.440945 -1.346457 0.464567 NaN

Part 6: Real CSIRO Coverage Span#

Before comparing sources you need to know exactly which years each one covers. sea['csiro'].notna() returns True where a CSIRO value exists, and .loc[mask, 'year'] picks the years for those rows. The output (1880, 2013) confirms the tide-gauge record spans 134 years. Measuring coverage directly from the data is better than trusting a description, because files are sometimes trimmed or extended.

csiro_years = sea.loc[sea['csiro'].notna(), 'year']
csiro_years.min(), csiro_years.max()
(np.int64(1880), np.int64(2013))

Part 7: Real NOAA Coverage Span#

The same check for the NOAA column shows the satellite era. Using notna() as a mask and taking the minimum and maximum year gives the output (1993, 2023): 31 years of satellite data. The two sources therefore share some years, from 1993 to 2013, which is what makes it possible to test whether they agree.

noaa_years = sea.loc[sea['noaa'].notna(), 'year']
noaa_years.min(), noaa_years.max()
(np.int64(1993), np.int64(2023))

Part 8: Real CSIRO Total Rise#

The total rise over each source's own span is the simplest headline figure. The code filters to rows where csiro is present, then subtracts the first value (.iloc[0]) from the last (.iloc[-1]). The output is 8.91, so tide gauges recorded about 8.91 inches of rise from 1880 to 2013. Comparing only two single years can be affected by year-to-year noise, which is why the later steps also fit a trend line.

csiro_rise = round(sea.loc[sea['csiro'].notna(), 'csiro'].iloc[-1] - sea.loc[sea['csiro'].notna(), 'csiro'].iloc[0], 2)
csiro_rise
np.float64(8.91)

Part 9: Real NOAA Total Rise#

Repeating the calculation for NOAA gives the satellite-era rise. The code filters to non-missing noaa values and subtracts the first from the last. The output is 3.9 inches between 1993 and 2023. That is less than half the CSIRO total but over a much shorter period of about 30 years compared with more than 130, which already suggests a faster recent pace.

noaa_rise = round(sea.loc[sea['noaa'].notna(), 'noaa'].iloc[-1] - sea.loc[sea['noaa'].notna(), 'noaa'].iloc[0], 2)
noaa_rise
np.float64(3.9)

Part 10: Real Both-Series Chart#

Plotting both series together is the quickest way to see how they relate. The code draws two lines with ax.plot against year: CSIRO in blue and NOAA in red. Matplotlib simply leaves gaps where values are NaN, so each line only appears over its own years. The chart is saved as sea_level_both_series.png with no inline output. In the image, look for the long, steady CSIRO climb and check whether the NOAA line sits on top of it during 1993 to 2013.

fig, ax = plt.subplots(figsize=(11, 6))
ax.plot(sea['year'], sea['csiro'], label='Real CSIRO Tide Gauges', color='steelblue', linewidth=2)
ax.plot(sea['year'], sea['noaa'], label='Real NOAA Satellite', color='firebrick', linewidth=2)
ax.set_xlabel('Real Year')
ax.set_ylabel('Real Sea Level Change, Inches')
ax.set_title('Real Global Mean Sea Level, CSIRO vs NOAA, 1880-2023')
ax.legend()
plt.tight_layout()
plt.savefig('sea_level_both_series.png', dpi=100)
plt.close()

Part 11: Real Overlap Years#

The overlap period is where you can directly test whether two methods tell the same story. The code keeps rows where both csiro and noaa are present by combining two notna() masks with &. The output (21, 1993, 2013) shows 21 shared years. Any comparison of the two sources should be restricted to these rows, otherwise you would be comparing different periods.

overlap = sea[sea['csiro'].notna() & sea['noaa'].notna()]
len(overlap), overlap['year'].min(), overlap['year'].max()
(21, np.int64(1993), np.int64(2013))

Part 12: Real Overlap Correlation#

Correlation measures how closely two series move together, on a scale from -1 to 1, where 1 means they rise and fall in perfect step. overlap['csiro'].corr(overlap['noaa']) calculates the Pearson correlation for the 21 shared years, rounded to four decimals. The output is 0.9773, a very strong agreement between tide gauges and satellites. Note that high correlation shows the two move together; it does not prove they give the same values, which the next step checks.

overlap_corr = round(overlap['csiro'].corr(overlap['noaa']), 4)
overlap_corr
np.float64(0.9773)

Part 13: Real Mean Absolute Difference#

Because correlation ignores level differences, you also measure how far apart the two readings are. The code subtracts NOAA from CSIRO for each overlap year, takes .abs() so negative and positive gaps do not cancel, and averages with .mean(). The output is 0.219, so the two sources differ by about a fifth of an inch on average. This mean absolute difference is easy to explain to non-technical readers because it is in the original units.

mean_abs_diff = round((overlap['csiro'] - overlap['noaa']).abs().mean(), 3)
mean_abs_diff
np.float64(0.219)

Part 14: Real Overlap Scatter Chart#

A scatter chart shows agreement point by point. ax.scatter plots each overlap year with its CSIRO value on the x-axis and NOAA value on the y-axis, using a square figure so the axes are visually comparable. The chart is saved as sea_level_overlap_scatter.png and is not displayed inline. In the image, points falling close to a straight diagonal line indicate strong agreement; any point far from the pattern marks a year where the methods disagreed.

fig, ax = plt.subplots(figsize=(7, 7))
ax.scatter(overlap['csiro'], overlap['noaa'], color='darkgreen')
ax.set_xlabel('Real CSIRO Sea Level, Inches')
ax.set_ylabel('Real NOAA Sea Level, Inches')
ax.set_title('Real CSIRO vs NOAA Agreement, 1993-2013 Overlap')
plt.tight_layout()
plt.savefig('sea_level_overlap_scatter.png', dpi=100)
plt.close()

Part 15: Real CSIRO Linear Trend#

A linear trend gives the average rate of rise across all years, which is more robust than comparing just the first and last values. np.polyfit(x, y, 1) fits a straight line (a polynomial of degree 1) and returns the slope and intercept; [0] takes the slope. The output is 0.0629, meaning CSIRO sea level rose about 0.063 inches per year on average from 1880 to 2013. The mask is needed because polyfit cannot handle NaN values.

csiro_mask = sea['csiro'].notna()
csiro_slope = round(np.polyfit(sea.loc[csiro_mask, 'year'], sea.loc[csiro_mask, 'csiro'], 1)[0], 4)
csiro_slope
np.float64(0.0629)

Part 16: Real NOAA Linear Trend#

Fitting the same kind of line to the NOAA data gives the satellite-era rate. The code masks out missing noaa values and calls np.polyfit with degree 1. The output slope is 0.1228 inches per year from 1993 to 2023. Because the two slopes cover different periods, comparing them tells you whether the recent rate differs from the long-term average.

noaa_mask = sea['noaa'].notna()
noaa_slope = round(np.polyfit(sea.loc[noaa_mask, 'year'], sea.loc[noaa_mask, 'noaa'], 1)[0], 4)
noaa_slope
np.float64(0.1228)

Part 17: Real Trend Acceleration Ratio#

A ratio turns two rates into one easy comparison. The code divides noaa_slope by csiro_slope and rounds to two decimals. The output is 1.95, meaning the recent satellite-era rise is almost twice the long-term average rate. Keep in mind the two slopes come from different instruments as well as different periods, though the strong overlap agreement gives some confidence in the comparison.

acceleration_ratio = round(noaa_slope / csiro_slope, 2)
acceleration_ratio
np.float64(1.95)

Part 18: Real Decade Comparison#

Averaging a whole decade at each end of the record shows the change in level while smoothing single-year noise. Each line filters the rows with two conditions joined by & and takes the mean of csiro. The output is (0.2, 8.4): the 1880s averaged 0.2 inches above the 1880 baseline, while 2004 to 2013 averaged 8.4 inches. The recent window ends at 2013 because that is the last full decade of CSIRO data.

decade_1880s = sea[(sea['year'] >= 1880) & (sea['year'] <= 1889)]['csiro'].mean()
decade_2004_2013 = sea[(sea['year'] >= 2004) & (sea['year'] <= 2013)]['csiro'].mean()
round(decade_1880s, 2), round(decade_2004_2013, 2)
(np.float64(0.2), np.float64(8.4))

Part 19: Real Decade Comparison Chart#

A two-bar chart makes the decade comparison instantly readable for any audience. ax.bar takes a list of two labels and a list of the two decade averages, with a different colour for each. The chart is saved as sea_level_decade_comparison.png with no inline output. In the image, expect a very short bar for the 1880s next to a much taller one for 2004 to 2013, matching the 0.2 and 8.4 inch averages.

fig, ax = plt.subplots(figsize=(7, 6))
ax.bar(['Real 1880s', 'Real 2004-2013'], [decade_1880s, decade_2004_2013], color=['steelblue', 'firebrick'])
ax.set_ylabel('Real Average Sea Level, Inches')
ax.set_title('Real Sea Level, First vs Real Final Full CSIRO Decade')
plt.tight_layout()
plt.savefig('sea_level_decade_comparison.png', dpi=100)
plt.close()

Part 20: Real Rate Per Decade#

Rates per year can look tiny, so expressing them per decade makes them easier to communicate. The code multiplies each slope by 10 and rounds. The output (0.63, 1.23) shows roughly 0.63 inches per decade across the long tide-gauge record and 1.23 inches per decade in the satellite era. Choosing a reporting unit your audience can picture is a small step that greatly improves how findings land.

csiro_rate_per_decade = round(csiro_slope * 10, 2)
noaa_rate_per_decade = round(noaa_slope * 10, 2)
csiro_rate_per_decade, noaa_rate_per_decade
(np.float64(0.63), np.float64(1.23))

Part 21: Real Error Bound Width#

Error bounds show how confident scientists are in each estimate, and checking how they change over time tells you which years to trust most. The code creates error_width by subtracting csiro_lower from csiro_upper, then returns the first and last widths among years with CSIRO data. The output shows about 1.91 inches in 1880, narrowing to about 0.70 inches in 2013. Measurement has become far more precise, so early values carry much more uncertainty.

sea['error_width'] = sea['csiro_upper'] - sea['csiro_lower']
sea.loc[sea['csiro'].notna(), 'error_width'].iloc[0], sea.loc[sea['csiro'].notna(), 'error_width'].iloc[-1]
(np.float64(1.90551181), np.float64(0.7007874009999995))

Part 22: Real Error Bound Chart#

Charting the uncertainty width over time shows whether precision improved gradually or in steps. The code plots error_width against year for rows with CSIRO data only, in purple. The figure is saved as sea_level_uncertainty.png and closed, so there is nothing inline. In the image, look for a general downward slope from about 1.9 inches to about 0.7 inches and note any sharp drops, which may reflect new tide gauges coming online.

fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(sea.loc[sea['csiro'].notna(), 'year'], sea.loc[sea['csiro'].notna(), 'error_width'], color='purple')
ax.set_xlabel('Real Year')
ax.set_ylabel('Real Uncertainty Range Width, Inches')
ax.set_title('Real CSIRO Sea Level Measurement Uncertainty Over Time')
plt.tight_layout()
plt.savefig('sea_level_uncertainty.png', dpi=100)
plt.close()

Part 23: Real Negative Lower Bound Years#

A negative lower bound means scientists cannot rule out that sea level was below the 1880 baseline in that year. (sea['csiro_lower'] < 0).sum() counts such years. The output is 18. Missing values compare as False, so the 10 years with no CSIRO data are not counted. You would expect these to be early years, when the rise was still small compared with the uncertainty; filter the rows to check.

negative_lower_years = (sea['csiro_lower'] < 0).sum()
negative_lower_years
np.int64(18)

Part 24: Real Merged Best-Estimate Series#

To report a single continuous series from 1880 to 2023, you merge the two sources. sea['noaa'].combine_first(sea['csiro']) takes the NOAA value where it exists and fills any gaps with the CSIRO value, so satellite data is preferred during the overlap. Counting NaN in the new best_estimate column gives 0, so every year now has a value. Be aware that this joins two different instruments, so a small step can appear where the sources switch over in 1993.

sea['best_estimate'] = sea['noaa'].combine_first(sea['csiro'])
sea['best_estimate'].isna().sum()
np.int64(0)

Part 25: Real Merged Series Total Rise#

With one merged series, you can state the total rise across the full span. The code drops any missing values, then subtracts the first value (1880, from CSIRO) from the last (2023, from NOAA). The output is 10.2 inches of rise from 1880 to 2023. Treat this as an approximate figure, since it compares readings from two different measurement systems.

merged_rise = round(sea['best_estimate'].dropna().iloc[-1] - sea['best_estimate'].dropna().iloc[0], 2)
merged_rise
np.float64(10.2)

Part 26: Saving the Real Enriched Dataset#

Saving the enriched table means later work can use the clean names, error_width and best_estimate without redoing these steps. to_csv(..., index=False) writes the file without the row index, and the code reloads it and compares shapes. The output is True, so nothing was lost in the round trip. Missing values are written as empty cells and read back as NaN.

sea.to_csv('sea_level_enriched.csv', index=False)
reloaded = pd.read_csv('sea_level_enriched.csv')
reloaded.shape == sea.shape
True

Part 27: Real Sanity Check, Full Span#

A row count check confirms that renaming, adding columns and merging have not accidentally removed or added years. len(sea) == 144 tests the current length against the original. The output is True, so every year from 1880 to 2023 is still present. Simple checks like this catch mistakes such as overwriting the table with a filtered version.

len(sea) == 144
True

Part 28: Real Sanity Check, No Duplicate Years#

Each year should appear exactly once, otherwise trends and decade averages would be distorted. sea['year'].nunique() counts distinct years, and comparing it with len(sea) tests whether every row has a unique year. The output is True, so there are no repeated years. This is a stricter check than duplicated(), which only flags rows identical in every column.

sea['year'].nunique() == len(sea)
True

Part 29: Real Top Finding Print#

The key finding is turned into a sentence that could open a report. The f-string inserts the CSIRO total rise and the acceleration ratio. The output states that sea level rose 8.91 inches from 1880 to 2013 by tide-gauge measurement and that the satellite era shows a pace 1.95 times the long-term average. Building sentences from variables means the wording updates automatically if the data is refreshed.

print(f'Global sea level genuinely rose {csiro_rise} inches from 1880 to 2013 by real tide-gauge measurement, and the real satellite era shows it rising at {acceleration_ratio} times that long-term average pace.')
Global sea level genuinely rose 8.91 inches from 1880 to 2013 by real tide-gauge measurement, and the real satellite era shows it rising at 1.95 times that long-term average pace.

Part 30: Real Recap Print#

The recap sums up how well the sources agree and what the combined record shows. The f-string uses len(sea), mean_abs_diff, len(overlap) and merged_rise. The output reports 144 years, agreement within 0.219 inches over a 21-year overlap, and 10.2 inches of total rise from 1880 to 2023 in the merged series. Mentioning how well the sources agree makes the headline number more credible to your audience.

print(f'Across {len(sea)} real years, two independent methods agreed within {mean_abs_diff} inches during their real {len(overlap)}-year overlap, and the real merged best-estimate series shows {merged_rise} inches of total rise from 1880 to 2023.')
Across 144 real years, two independent methods agreed within 0.219 inches during their real 21-year overlap, and the real merged best-estimate series shows 10.2 inches of total rise from 1880 to 2023.

Wrap-Up: What You Learned#

  • This real lesson combined two independent government sea level sources, real CSIRO tide gauges from 1880 to 2013 and real NOAA satellites from 1993 to 2023, honestly explaining why so many real years are missing from each individual column.
  • During their real twenty-one-year overlap, the two genuinely different measurement methods correlated at 0.9773 and agreed within about a real fifth of an inch on average.
  • Real sea level is genuinely rising almost twice as fast in the recent satellite era as it did across the real full historical CSIRO record.
  • Building one real merged best-estimate column, preferring the newer real source when both exist, is an honest way to combine real datasets with different real coverage windows.
  • Next video: a real global earthquake dataset, moving from a slow-moving climate trend to a real sudden environmental hazard.

Practice on your own

  • Fit separate np.polyfit trends to the CSIRO data for 1880 to 1949 and 1950 to 2013 and compare the two slopes per decade.
  • Find the overlap year where CSIRO and NOAA differ the most, using (overlap['csiro'] - overlap['noaa']).abs().idxmax(), and check whether it falls early or late in the overlap.
  • Plot best_estimate as a single line and mark 1993, where the series switches from CSIRO to NOAA, with ax.axvline to see whether a visible step appears.

The next lesson moves from a slow climate trend to a sudden hazard, using a global earthquake 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.