Section 4 · Lesson 3
Correlation vs causation
Measure association with Pearson's r and Spearman's rho, and see how a hidden third variable can create a strong correlation.
Days when we spend more on ads are also days with more conversions. Does spending more cause more conversions? Maybe, but a correlation alone can’t tell you. This lesson shows how to measure association and how to stop it from fooling you.
Pearson’s correlation (r)
Pearson’s r measures the strength and direction of a linear relationship between two numeric variables:
r = covariance(x, y) / (sd_x * sd_y)
≈ average of (z-score of x × z-score of y)
- r ranges from -1 (perfect downhill line) through 0 (no linear relationship) to +1 (perfect uphill line).
- When x is above its mean and y is also above its mean, the product of z-scores is positive; lots of those push r toward +1.
- r² is the share of the variation in y that a straight line on x accounts for. r = 0.57 means r² ≈ 0.32: about a third.
What r can’t see
- Only straight lines. A strong curved relationship (like diminishing returns on spend) can have a modest r.
- Outliers. One extreme campaign-day can inflate or hide a correlation.
- Spearman’s rho is Pearson’s r computed on the ranks of the values. It measures any consistently increasing (monotonic) relationship and is much less sensitive to outliers and skew. On skewed ad data it is often noticeably higher than Pearson’s r.
- The p-value from
pearsonrtests H0 “true correlation = 0”. With 1,561 rows even a weak r gets a tiny p-value, so focus on the size of r, not just significance.
Correlation is not causation
Three common reasons two things move together without one causing the other:
- Confounding: a third variable drives both. On days with more active campaigns, total spend and total conversions rise. That alone produces a daily correlation near 0.95, and it drops sharply once you look at spend and conversions per active campaign.
- Reverse causation: budgets often get raised on campaigns that already convert well. Then conversions are causing spend, not the other way around.
- Coincidence and selection: scan enough metrics and some will line up by chance. Analyzing only campaigns that survived (weren’t paused) can also create patterns.
The reliable way to show causation is a randomized experiment, like the A/B test in the previous lesson: randomization balances every confounder, known or unknown, between groups. In advertising, holdout or “lift” tests do the same for spend: randomly withhold ads from some users or regions and compare.
In Python
import pandas as pd
from scipy import stats
ds = pd.read_csv("daily_stats.csv")
ds["spend"].corr(ds["conversions"]) # Pearson (default)
ds["spend"].corr(ds["conversions"], method="spearman") # Spearman
ds[["impressions", "clicks", "spend", "conversions"]].corr() # full correlation matrix
stats.pearsonr(ds["spend"], ds["conversions"]) # r and its p-value
stats.spearmanr(ds["spend"], ds["conversions"]) # rho and its p-value
DataFrame.corr() returns a table with the correlation of every pair of columns, which is a
fast way to scan a dataset.
In the real world
“Spend and conversions are 95% correlated, so let’s double the budget” is one of the most expensive sentences in marketing. Doubling spend can push you into pricier auctions, broader audiences and diminishing returns, and the correlation was partly driven by how many campaigns were running. Use correlations to generate hypotheses and spot data problems; use experiments to make investment decisions.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Spend vs conversions
DoneLoad daily_stats.csv (one row per campaign per day). Using scipy.stats.pearsonr on spend and conversions, create:
r: Pearson's correlation coefficient, rounded to 3 decimalsp_value: the p-value for H0 "the true correlation is 0" (no rounding)r_squared: r², computed from the unrounded r and then rounded to 3 decimals
Need a hint?
stats.pearsonr(x, y)returns a result with.statistic(r) and.pvalue.ds["spend"].corr(ds["conversions"])gives the same r with pandas.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
from scipy import stats
ds = pd.read_csv("daily_stats.csv")
r = None
p_value = None
r_squared = None
print(r, p_value, r_squared)
Files in the working directory
ab_test.csv (4,000 rows)daily_stats.csv (1,561 rows)orders.csv (900 rows)campaigns.csv (40 rows)Rank correlation and a near-zero r
DoneUsing daily_stats.csv:
rho: Spearman's rank correlation betweenspendandconversions, rounded to 3 decimalsr_spend_ctr: Pearson's correlation betweenspendand CTR (clicks / impressions),
rounded to 3 decimals
Compare rho to Pearson's r from the previous task, and notice how close to zero r_spend_ctr is.
Need a hint?
s1.corr(s2, method="spearman")ranks both columns, then computes Pearson on the ranks.scipy.stats.spearmanr(x, y).statisticgives the same rho.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
ds = pd.read_csv("daily_stats.csv")
ds["ctr"] = ds["clicks"] / ds["impressions"]
rho = ds["spend"].corr(ds["conversions"]) # which method is this?
r_spend_ctr = None
print(rho, r_spend_ctr)
Files in the working directory
ab_test.csv (4,000 rows)daily_stats.csv (1,561 rows)orders.csv (900 rows)campaigns.csv (40 rows)Find the confounder
DoneAdd up daily_stats.csv by date to get one row per day with:
- total
spend, totalconversions, andactive= the number of campaigns with a row
that day
Then create (Pearson, each rounded to 3 decimals):
r_daily: correlation between daily total spend and daily total conversionsr_active_spend: correlation betweenactiveand daily total spendr_per_campaign: correlation between spend per active campaign and conversions
per active campaign (divide each daily total by active)
Need a hint?
- Inside
.agg(),active=("campaign_id", "count")counts rows per date. - Dividing two columns of the same DataFrame works element by element:
daily["spend"] / daily["active"].
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
ds = pd.read_csv("daily_stats.csv")
daily = ds.groupby("date").agg(
spend=("spend", "sum"),
conversions=("conversions", "sum"),
# TODO: add active = number of campaigns that day
)
r_daily = None
r_active_spend = None
r_per_campaign = None
print(r_daily, r_active_spend, r_per_campaign)
Files in the working directory
ab_test.csv (4,000 rows)daily_stats.csv (1,561 rows)orders.csv (900 rows)campaigns.csv (40 rows)