Statistical modeling with Python · Lesson 7 of 16

Correlation in Python: Pearson and Spearman

Measure how two columns move together with Pearson and Spearman correlation, test it with SciPy, and avoid the classic traps.

About 14 minutes · code runs in your browser, nothing to install

Correlation is a number between −1 and 1 that says how closely two columns move together. +1: they rise together on a perfect straight line. −1: one rises as the other falls. 0: no straight-line link. It is often the first thing to check before a regression.

Pearson correlation

Pearson's r measures a straight-line link. df.corr() gives every pair at once; stats.pearsonr gives one pair with a p-value (for the null hypothesis "no correlation").

Pythoneditable
import pandas as pd
from scipy import stats

df = pd.DataFrame({
    "temp": [14, 16, 19, 21, 23, 25, 27, 30, 32, 34],
    "ice_creams": [110, 128, 151, 160, 182, 190, 215, 240, 251, 270],
    "umbrellas": [30, 26, 25, 19, 17, 20, 14, 12, 9, 11],
})
print(df.corr().round(2))
res = stats.pearsonr(df["temp"], df["ice_creams"])
p = "p < 0.001" if res.pvalue < 0.001 else f"p = {res.pvalue:.3f}"
print(f"r = {res.statistic:.3f}, {p}")
Output
            temp  ice_creams  umbrellas
temp        1.00        1.00      -0.96
ice_creams  1.00        1.00      -0.96
umbrellas  -0.96       -0.96       1.00
r = 0.998, p < 0.001

Daily sales at a beach kiosk on ten days.

How to read it: warmer days go with more ice creams (r = 0.998, almost a perfect straight line) and fewer umbrellas (r = −0.96). The p-value is tiny, so the link is very unlikely to be chance. Note that ice creams and umbrellas are also strongly (negatively) correlated, but neither causes the other: temperature drives both. Correlation is not causation.

Spearman correlation: ranks instead of values

Spearman's rho first replaces values by their ranks (1st, 2nd, 3rd…) and then correlates the ranks. It measures any link that always goes in one direction, even if curved, and is not thrown off by one extreme value.

Pythoneditable
from scipy import stats

x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [1, 2, 4, 8, 16, 32, 64, 128]   # always rising, but curved
print(f"Pearson:  {stats.pearsonr(x, y).statistic:.3f}")
print(f"Spearman: {stats.spearmanr(x, y).statistic:.3f}")
Output
Pearson:  0.850
Spearman: 1.000

The traps

  • Outliers: one extreme point can create or hide a correlation (example below).
  • Curves: a perfect U-shaped link can have r = 0. Always draw a scatter plot.
  • Hidden third variable: ice creams and umbrellas, through temperature.
  • Restricted range: among only the tallest players, height barely correlates with points scored, though over everyone it does.
Pythoneditable
from scipy import stats

x = [-3, -2, -1, 0, 1, 2, 3]
y = [9, 4, 1, 0, 1, 4, 9]        # y = x squared: a perfect U
r = stats.pearsonr(x, y).statistic
print(f"U shape: r = {abs(r):.3f}")  # abs(): r is 0, up to tiny rounding

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 20]
b = [5, 3, 6, 2, 5, 4, 3, 6, 4, 25]
print(f"with outlier:    r = {stats.pearsonr(a, b).statistic:.3f}")
print(f"without outlier: r = {stats.pearsonr(a[:-1], b[:-1]).statistic:.3f}")
print(f"Spearman with outlier: {stats.spearmanr(a, b).statistic:.3f}")
Output
U shape: r = 0.000
with outlier:    r = 0.864
without outlier: r = 0.033
Spearman with outlier: 0.295

The U shape is a perfect relationship with r = 0. The second pair has no link at all in the first nine points; one extra point (20, 25) makes Pearson report a strong 0.86. Spearman, using ranks, is much less impressed.

Pythoneditable
import matplotlib.pyplot as plt
from scipy import stats

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 20]
b = [5, 3, 6, 2, 5, 4, 3, 6, 4, 25]
print(f"r = {stats.pearsonr(a, b).statistic:.2f}, driven by one point")

plt.scatter(a[:-1], b[:-1], color="steelblue", label="nine normal points")
plt.scatter(a[-1:], b[-1:], color="crimson", s=80, label="one outlier")
plt.title("One point makes a strong correlation")
plt.legend()
plt.show()
Output
r = 0.86, driven by one point
Chart drawn by this code

Always look at the scatter plot before trusting r.

✎ Exercise

Ten flats: size in m² and monthly rent in €. Print the Pearson and Spearman correlations with 3 decimals.

Hint: stats.pearsonr(size, rent).statistic and stats.spearmanr(size, rent).statistic.

Your codewrite your answer, then Run
from scipy import stats

size = [35, 42, 50, 55, 61, 68, 75, 82, 90, 110]
rent = [620, 700, 760, 820, 800, 930, 990, 1010, 1150, 1400]
# your code here

Expected output:

Pearson:  0.988
Spearman: 0.988
Show a solution
Solutioneditable
from scipy import stats

size = [35, 42, 50, 55, 61, 68, 75, 82, 90, 110]
rent = [620, 700, 760, 820, 800, 930, 990, 1010, 1150, 1400]
print(f"Pearson:  {stats.pearsonr(size, rent).statistic:.3f}")
print(f"Spearman: {stats.spearmanr(size, rent).statistic:.3f}")
Output
Pearson:  0.988
Spearman: 0.988

Check yourself

1. Two columns have Pearson r = 0. What can you say?

2. Why might Spearman differ a lot from Pearson?

3. Shoe size and reading skill are correlated in children. Why?

Spotted a mistake on this page? Tell us