Correlation vs causation is the first warning every analyst hears and the one most often forgotten. A correlation tells you two numbers move together. It does not tell you why, and it can even point the wrong way. This guide shows three reproducible ways correlation misleads: a trend that reverses when you split the data, strong correlations between random series, and a relationship the coefficient cannot see at all.
The first example uses the Palmer penguins data (333 complete rows from three species) from the seaborn sample data. The others are simulations, labelled as such. Code was run with pandas 3.0.5, SciPy 1.18.1 and statsmodels 0.15.0.

A correlation that changes sign
We measure two things on each penguin: bill length and bill depth, both in millimetres. Intuitively, a longer bill should go with a deeper bill. Let us check the correlation on the whole dataset.
import pandas as pd, numpy as np
from scipy import stats
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
d = pd.read_csv(url).dropna()
print(d.shape, d.species.value_counts().to_dict())
r, p = stats.pearsonr(d.bill_length_mm, d.bill_depth_mm)
print(f"all penguins: r = {r:.3f}, p = {p:.5f}")Output:
(333, 7) {'Adelie': 146, 'Gentoo': 119, 'Chinstrap': 68}
all penguins: r = -0.229, p = 0.00003The correlation is negative: r = -0.229, with p = 0.00003. Taken at face value, penguins with longer bills have shallower bills, and the p-value says the pattern is not a fluke. Now split by species.
for sp, g in d.groupby("species"):
r, p = stats.pearsonr(g.bill_length_mm, g.bill_depth_mm)
print(f"{sp:10s} n={len(g):3d} r = {r:+.3f} mean length {g.bill_length_mm.mean():.1f} mean depth {g.bill_depth_mm.mean():.1f}")Output:
Adelie n=146 r = +0.386 mean length 38.8 mean depth 18.3
Chinstrap n= 68 r = +0.654 mean length 48.8 mean depth 18.4
Gentoo n=119 r = +0.654 mean length 47.6 mean depth 15.0Inside every species the correlation is positive: +0.386 for Adelie, +0.654 for Chinstrap and +0.654 for Gentoo. The overall negative sign comes from comparing species, not individual penguins. Gentoo have long bills (mean 47.6 mm) but shallow ones (15.0 mm); Adelie have short bills (38.8) and deep ones (18.3). Mix the groups and the between-species gap swamps the within-species trend. This is Simpson’s paradox, and species is the confounder: it affects both measurements.
A regression shows the same flip in terms of slopes. Without species, depth falls 0.082 mm for every extra millimetre of bill length (95% interval -0.120 to -0.044). With species included, depth rises 0.200 mm per millimetre (interval 0.166 to 0.235).
import statsmodels.formula.api as smf
naive = smf.ols("bill_depth_mm ~ bill_length_mm", d).fit()
adjusted = smf.ols("bill_depth_mm ~ bill_length_mm + C(species)", d).fit()
print("slope without species:", naive.params["bill_length_mm"].round(4), naive.conf_int().loc["bill_length_mm"].round(3).tolist())
print("slope with species: ", adjusted.params["bill_length_mm"].round(4), adjusted.conf_int().loc["bill_length_mm"].round(3).tolist())Output:
slope without species: -0.0823 [-0.12, -0.044]
slope with species: 0.2004 [0.166, 0.235]Which number is right? Neither is a causal effect. Stretching a particular penguin’s bill by a millimetre is not something the data tells us about. What the species-adjusted slope answers is the narrower question “among penguins of the same species, how do the two measurements move together?”, and for most questions about shape that is the useful one. Knowing which grouping variable to include comes from understanding the biology, not from the data alone. Also, this only works because we recorded species. A confounder that is not in the table cannot be adjusted for. For a model that handles several inputs at once, see logistic regression in Python, which makes the “other things equal” reading explicit.
Strong correlations between unrelated series
A second trap: two series that trend over time often correlate even when nothing connects them. To show it without picking on a real pair of variables, we simulate 1,000 pairs of independent random walks (each a running sum of random steps, 100 points long) and test every pair.
rng = np.random.default_rng(0)
walk_p, walk_r, iid_p = [], [], []
for _ in range(1000):
a, b = np.cumsum(rng.normal(size=100)), np.cumsum(rng.normal(size=100))
r, p = stats.pearsonr(a, b)
walk_p.append(p); walk_r.append(abs(r))
iid_p.append(stats.pearsonr(rng.normal(size=100), rng.normal(size=100))[1])
print("independent random walks: share with p < 0.05 =", np.mean(np.array(walk_p) < 0.05))
print("median |r| =", round(float(np.median(walk_r)), 2), "| share with |r| > 0.5 =", np.mean(np.array(walk_r) > 0.5))
print("independent noise: share with p < 0.05 =", np.mean(np.array(iid_p) < 0.05))Output:
independent random walks: share with p < 0.05 = 0.765
median |r| = 0.43 | share with |r| > 0.5 = 0.42
independent noise: share with p < 0.05 = 0.042Among pairs of random walks that have nothing to do with each other, 76.5% came out “significant” at the 5% level, the median correlation was 0.43 in absolute size, and 42% had |r| above 0.5. For independent noise, 4.2% were significant, as the 5% rule promises. The p-value assumes independent observations, and in a trending series each point depends on the one before it. If you correlate two variables that both rise over time, such as sales and temperature or users and servers, difference the series first or compare changes rather than levels. This is a simulation, not a statement about any real pair. This is why collections of “spurious correlations” are so easy to produce from real time series.
A relationship the correlation coefficient cannot see
x = np.linspace(-3, 3, 100)
print("x vs x squared: r =", round(float(np.corrcoef(x, x ** 2)[0, 1]), 3))Output:
x vs x squared: r = 0.0Here y is exactly x squared, a perfect and deterministic link, and Pearson’s r rounds to 0.0. Correlation measures straight-line association only. Always plot the data, and when relationships are monotonic but curved, Spearman’s rank correlation is the safer summary. On the penguin data Spearman gives -0.214 overall, close to Pearson’s -0.229, so the sign flip is not an artifact of the coefficient.
Correlation vs causation: what would it take to claim causation?
Three things usually, and none comes from a correlation table. First, a design that assigns the cause at random, like the experiment in A/B test significance in Python, where players were randomly given one version or the other, so a difference in retention can be traced to the change. Second, if you cannot randomise, you need a defensible story about confounders, data on them, and an honest sense of what you did not measure. Third, a check that the timing makes sense: the cause comes before the effect. The statistics here can rule out chance, but they cannot rule out a hidden variable.
A quick checklist before you write “X causes Y”: Did you plot the data? Could a third variable drive both, and did you split by it? Are the observations independent, or is this a time series? Is there a plausible mechanism, and can you test it with an experiment? To compute a correlation on your own numbers, use the free correlation calculator, and for a first pass on a new dataset see exploratory data analysis in Python. Splitting by group is covered in pandas groupby explained.
The SciPy documentation for pearsonr explains the assumptions behind the p-value, and the penguin data comes from the palmerpenguins project (via the seaborn-data copy). Not covered: causal inference methods such as instrumental variables, difference-in-differences and DAG-based adjustment.
FAQ
What is the difference between correlation and causation?
Correlation means two variables move together. Causation means changing one produces a change in the other. The penguin data shows a negative correlation overall while the relationship within each species is positive, so the correlation alone told us the wrong story.
Can a correlation be zero when there is a relationship?
Yes. Pearson’s r only measures straight-line association. For y = x squared over a symmetric range, r is 0 to numerical precision.
What is Simpson’s paradox?
A trend that appears in the combined data but reverses when you split by a third variable. Here, bill length and depth correlated at -0.23 overall and at +0.39 to +0.65 within each species.
How do I test for causation in Python?
Libraries cannot prove causation from observational data. The strongest approach is a randomised experiment, analysed with a test such as a two-proportion z-test. Without one, you adjust for known confounders with regression and state the limits.
