In summer, ice-cream sales and drownings rise together. Does ice cream cause drowning? Of course not: hot weather sends people both to ice-cream stalls and into the sea. Everyone laughs at that example. Yet the same mistake, in less obvious forms, appears in news headlines, business reports and machine learning projects every day. "Customers who use our app daily spend more, so we should push notifications to make them use it daily." Maybe. Or maybe customers who already love the brand do both.
A correlation tells you two columns move together. It doesn't tell you why. You'll meet the four common reasons for a correlation without a cause, see a famous paradox in real penguin data where the correlation flips sign, and learn what it takes to show causation, and why a predictive model doesn't need it but a business decision does.
What you need first: correlation explained and conditional probability explained.
Key terms
- Causation: changing one thing changes the other. If you intervene on x, y responds.
- Confounder (or lurking variable): a third variable that drives both x and y, creating a correlation between them.
- Reverse causation: y causes x, rather than x causing y.
- Spurious correlation: a correlation that appears by chance, with no real link.
- Selection bias: a correlation created by which rows ended up in the data.
- Simpson's paradox: a trend that appears in the whole data but reverses inside every group.
- Randomised experiment: a test where chance decides who gets the treatment, so nothing else can explain the difference. The gold standard for causation.
Reason 1: a confounder drives both
Simulate a year of summer days. Temperature drives both ice-cream sales and the number of swimmers who get into trouble. Ice cream has no effect on drownings in this simulation, by construction:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(8)
temp = rng.uniform(18, 40, 365) # daily temperature, °C
ice_cream = 20 * temp + rng.normal(0, 60, 365) # sales depend on heat only
drownings = rng.poisson(np.clip(0.15 * (temp - 15), 0, None)) # also depend on heat only
days = pd.DataFrame({"temp": temp, "ice_cream": ice_cream, "drownings": drownings})
print("correlation, ice cream vs drownings:", round(days["ice_cream"].corr(days["drownings"]), 2))
correlation, ice cream vs drownings: 0.46
rng.poisson(...)draws a count of incidents for each day, with a higher average on hotter days (a Poisson distribution).np.clip(..., 0, None)makes sure the average is never negative.
A clear positive correlation, even though ice cream causes nothing. Now hold temperature fixed: compare only days with similar temperatures. If ice cream really caused drownings, the correlation would survive inside each band. Predict what happens:
days["band"] = pd.cut(days["temp"], bins=[18, 23, 28, 33, 40])
print(days.groupby("band", observed=True).apply(lambda g: round(g["ice_cream"].corr(g["drownings"]), 2), include_groups=False))
band
(18, 23] 0.03
(23, 28] -0.07
(28, 33] 0.04
(33, 40] 0.07
dtype: float64
pd.cut sorts each day into a temperature band; then the correlation is computed separately inside each band.
Within each band, the correlation shrinks towards 0. Once you account for the confounder, the link mostly disappears. That's the main tool for spotting a confounder: compare like with like. Data analysts do this by splitting into groups; statisticians do it by adding the confounder to a regression model.
Reason 2: the cause runs the other way
Districts with more police have more crime. Do police cause crime? More likely, more crime leads cities to send more police. People who use a walking stick tend to be less steady on their feet; the stick doesn't cause the unsteadiness. Data can't tell you which way the arrow points; knowledge of how the world works, and the order in which things happened, can.
Reason 3: pure chance
Search through enough pairs of unrelated columns and some will be correlated by luck. Watch it happen with 200 completely random columns of 20 values each:
noise = pd.DataFrame(rng.normal(size=(20, 200)))
corr = noise.corr().abs().to_numpy()
np.fill_diagonal(corr, 0)
print(f"{200 * 199 // 2:,} pairs of random columns; largest |correlation| = {corr.max():.2f}")
19,900 pairs of random columns; largest |correlation| = 0.80
np.fill_diagonal(corr, 0) blanks out each column's perfect correlation with itself, so the maximum is between two different columns.
Among almost 20,000 pairs of pure noise, the best one has a strong correlation. That's how websites full of "spurious correlations" (cheese eaten against deaths by bedsheet tangling) are made: search enough pairs, report the best. With small samples and many comparisons, strong-looking correlations are cheap. The hypothesis testing module returns to this as the multiple testing problem.
Reason 4: selection creates the pattern
A college admits students with a high total of an entrance exam score and an interview score. Among admitted students, the two scores are negatively correlated: those with weaker exams must have had stronger interviews to get in. In the whole applicant pool, there may be no correlation at all. The pattern was created by which rows got into the data. The same thing happens with data on approved loans only, hired employees only, or customers who didn't churn yet.
Simpson's paradox: the trend that flips
Here's a real dataset where the correlation reverses. Across all penguins, is a longer bill linked to a deeper or a shallower bill?
Download the data: penguins.csv (15 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("penguins.csv").
import seaborn as sns
penguins = sns.load_dataset("penguins").dropna(subset=["bill_length_mm", "bill_depth_mm"])
print("all penguins:", round(penguins["bill_length_mm"].corr(penguins["bill_depth_mm"]), 2))
print(penguins.groupby("species").apply(lambda g: round(g["bill_length_mm"].corr(g["bill_depth_mm"]), 2), include_groups=False))
all penguins: -0.24
species
Adelie 0.39
Chinstrap 0.65
Gentoo 0.64
dtype: float64
Across all penguins, the correlation is negative: longer bills go with shallower bills. Within every single species, it's positive. The chart shows why:
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2), sharey=True)
axes[0].scatter(penguins["bill_length_mm"], penguins["bill_depth_mm"], color="#57534e", s=14)
axes[0].set_title("All penguins together: a falling trend")
for species, colour in zip(["Adelie", "Chinstrap", "Gentoo"], ["#c2410c", "#d9a05a", "#0f766e"]):
g = penguins[penguins["species"] == species]
axes[1].scatter(g["bill_length_mm"], g["bill_depth_mm"], color=colour, s=14, label=species)
slope, intercept = np.polyfit(g["bill_length_mm"], g["bill_depth_mm"], 1)
xs = np.linspace(g["bill_length_mm"].min(), g["bill_length_mm"].max(), 10)
axes[1].plot(xs, slope * xs + intercept, color=colour, linewidth=2.5)
axes[1].set_title("Split by species: every trend rises")
axes[1].legend()
for ax in axes:
ax.set_xlabel("Bill length (mm)")
axes[0].set_ylabel("Bill depth (mm)")
plt.tight_layout()
plt.show()
np.polyfit(x, y, 1) fits the best straight line through each species' points and returns its slope and intercept, which are used to draw the line.
Species is the confounder. Gentoos have long but shallow bills, so they pull the overall trend down. Within each species, bigger penguins simply have bigger bills in both directions. This is Simpson's paradox: a trend in combined data that reverses inside every group. A model or report that ignored species would get the relationship backwards.
How do you show causation?
- Randomised experiments. Let chance decide who gets the treatment: half of users see the new checkout page, half the old. Because the split is random, the two groups are alike in every other way on average, so any difference in purchases is caused by the page. This is an A/B test, and it's the main way tech companies make decisions. The hypothesis testing module includes an A/B testing project.
- When experiments are impossible (you can't randomly assign smoking), researchers combine careful comparisons that adjust for confounders, natural experiments, evidence from many studies, and a plausible mechanism. That's how smoking was shown to cause cancer.
What this means for machine learning
- Prediction doesn't need causation. A model can use the number of umbrellas sold to predict rain, even though umbrellas don't cause rain. For pure forecasting, any reliable correlation helps.
- Decisions do. If a churn model finds that customers who contacted support churn more, that doesn't mean stopping them contacting support will keep them. Unhappy customers both complain and leave. Acting on a predictive model's features as if they were causes is a common and expensive mistake.
- Correlations can break. A relationship driven by a confounder holds only while the confounder behaves the same way. Change the situation, and the model's pattern can vanish: another form of distribution shift.
- Fairness: features correlated with caste, religion or gender can let a model discriminate even when those columns are removed. A correlation doesn't need a cause to cause harm.
Common mistakes
- Reading a correlation as a cause. Ask: could a confounder, reverse cause, chance or selection explain it?
- Ignoring groups. Check whether the trend holds within each category; Simpson's paradox can flip it.
- Trusting the best of many correlations. Search enough pairs and something will look strong.
- Treating a model's important features as levers. Predictive importance isn't causal effect.
Practice
- Children with bigger shoe sizes have better reading scores. Suggest a confounder.
Show the answer
Age. Older children have bigger feet and read better. Within one age group, the correlation would mostly vanish.
- Predict, then check: in the simulated summer, what's the correlation between temperature and drownings? Is it larger or smaller than ice cream and drownings?
Show the answer
Larger: temperature is the real driver, and ice cream is only linked through it.
print(round(days["temp"].corr(days["drownings"]), 2), round(days["ice_cream"].corr(days["drownings"]), 2))
0.52 0.46
- A study finds that people who drink a glass of wine a day live longer than people who drink none. Give one confounder and one form of reverse causation.
Show the answer
Confounder: income or social life, which can be linked to both moderate drinking and health. Reverse causation: some people drink nothing because they're already ill, so the "non-drinkers" group includes sicker people.
- Which of the four reasons explains each: (a) a bank studies only approved loans and finds that low-income borrowers default less; (b) towns with more hospitals have more deaths?
Show the answer
(a) Selection: low-income applicants were approved only if they had other strong signs of reliability. (b) A confounder, population size: bigger towns have more of both. Reverse causation also plays a part, since places with more sick people need more hospitals.
- Your churn model's most important feature is "number of support tickets". Your manager wants to reduce churn by making it harder to file tickets. What do you say?
Show the answer
The model shows tickets predict churn, not that they cause it. Unhappy customers both file tickets and leave; blocking tickets would hide the problem and probably make customers angrier. To learn what reduces churn, run an experiment, such as offering faster support to a random half of at-risk customers.
Interview questions
Correlation does not imply causation. What are the main alternative explanations for a correlation?
Confounding (a third variable drives both), reverse causation, chance (especially with small samples or many comparisons), and selection bias (how the data was collected creates the association). Causation is best established with randomised experiments; otherwise with careful adjustment, natural experiments and domain knowledge.
What is Simpson's paradox? Give an example.
A trend that appears in aggregated data but reverses within each subgroup, because a confounding grouping variable is distributed differently across groups. In the penguins dataset, bill length and depth are negatively correlated overall but positively correlated within each species, because Gentoos have long, shallow bills.
Key takeaways
- A correlation shows two columns move together; it doesn't say why.
- Four common reasons for correlation without causation: confounders, reverse causation, chance and selection.
- Compare like with like: a correlation that disappears within groups was driven by the grouping variable.
- Simpson's paradox can reverse a trend completely, as with penguin bills.
- Randomised experiments show causation; predictive models only need correlation, but decisions need causes.
Frequently asked questions
Can correlation ever suggest causation?
It can be a clue worth investigating, especially with a plausible mechanism, the right time order and no obvious confounders. But on its own it's never proof.
Is a strong correlation more likely to be causal than a weak one?
Not necessarily. Ice cream and drownings can be strongly correlated with no causal link, and a real cause can have a weak correlation if many other things also affect the outcome.
What's causal inference?
A field of statistics and ML that estimates causal effects from data, using experiments or methods that adjust for confounders. It's an advanced topic beyond this course's scope for now.
What to learn next
- See every pair of columns at once in correlation matrix and heatmap in Python.
- Revisit how correlation is measured in correlation explained.
- Review how conditions change probabilities in conditional probability explained.