← Data analysis with Python

Correlation is not causation

Measure how strongly two columns move together, and be careful what you conclude.

Start this lesson

The correlation coefficient r measures how closely two numeric columns follow a straight-line pattern. It runs from -1 to 1: near 1 means they rise together, near -1 means one falls as the other rises, near 0 means no straight-line pattern. In pandas, df["a"].corr(df["b"]) computes it. But correlation is not causation. Ice cream sales and sunburns are strongly correlated, yet ice cream does not cause sunburn: hot sunny weather drives both. A hidden third factor like that is called a confounder.

import io
import pandas as pd

csv_text = """name,group,math,reading,hours
Amara,A,88,92,6
Ben,A,72,80,3
Chen,B,95,85,8
Dalia,B,64,70,2
Emeka,A,79,88,5
Fatima,B,91,94,7
Gus,A,58,65,1
Hana,B,83,77,5
"""
scores = pd.read_csv(io.StringIO(csv_text))
print(round(scores["hours"].corr(scores["math"]), 2))
print(round(scores["hours"].corr(scores["reading"]), 2))
print(scores[["math", "reading", "hours"]].corr().round(2))

Hours and math have r of about 0.99, a very strong positive relationship in this small group. .corr() on a table gives every pair at once. Even so, this data alone cannot prove that studying caused the higher scores; for example, students who already like math may both study more and score higher.

To show causation, researchers use experiments, for example randomly assigning who gets a tutoring program, so that confounders are balanced out.

r only measures straight-line patterns. A strong curved pattern can still have r near 0, so always look at the scatter plot too.