…
…
Statistics and Data Analysis Fundamentals · Lesson 37 / 44 · Correlation and causation
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The product team has prepared a presentation: "The return rate is 7.9% on mobile and 6.2% on desktop. The mobile experience is bad and increases returns; we must rebuild the mobile app." The numbers are correct, but the second half of the sentence is a cause-and-effect claim. In this lesson you will test this claim, and the "ads bring visitors" claim from the previous lesson, with data.
In the previous lesson you found r = 0.80 between ad spend and visitors, and you ended the lesson with a question: if both ads and visitors are high on weekends, what is the real effect of the ads? In this lesson you will see the difference between a relationship and a cause, first as a concept and then with data. At the end of the lesson you will build the table below yourself and you will be able to defend the sentence under it:
Outputdevice desktop mobile
Beauty 0.049 0.031
Books 0.023 0.014
Clothing 0.212 0.159
Electronics 0.037 0.021
Home & Living 0.041 0.024
Total 0.062 0.079
Standard 0.062 0.042The high return rate on mobile does not come from the mobile experience. It comes from the large share of Clothing orders on mobile: in every category the mobile rate is lower, and when you compare the two devices with the same category mix, mobile is 4.2% and desktop is 6.2%.
In this lesson you will:
In lesson 3 you separated observation from experiment: in observational data you do not form the groups, people choose them themselves. For this reason, seeing two things change together in observational data does not show that one causes the other. Let's see this with the first example in every statistics book. In a seaside town, the correlation between monthly ice cream sales and drowning cases is very high. Does ice cream cause drowning? Of course not. There is a third thing behind both: hot weather. When the weather gets warm, more ice cream is sold and more people go into the sea.
Hot weather here is a confounder: a third variable that affects both the explanatory variable (ice cream sales) and the response (drowning), and creates a false or inflated relationship between them. The confounder is the first and most common alternative explanation of an observational relationship. But it is not the only one. When you see a relationship, three other explanations should come to mind.
First, a confounder. Something else may be affecting both (hot weather, weekend, product category).
Second, reverse direction. Cause and effect may have swapped places. On average, people who are in the hospital are in worse health than people who are not. This does not mean that the hospital makes people sick; sick people go to the hospital. In the data, "being in the hospital" and "poor health" appear together, but the arrow points the other way.
Third, chance or selection. In a small dataset, two things can appear together by accident; you tested this with tests in lessons 27–34. Or the data may have passed through a filter that shapes the result from the start: a survey filled in only by satisfied customers produces the result "90% of customers are satisfied" all by itself. This is the selection bias from lesson 3.
There is one way to remove all three explanations in a single move: random assignment. If you split people into two groups by a coin toss and apply the change to only one of them, everything such as hot weather, weekend, and category is spread equally across the two groups on average; and because you decide who goes into which group, the arrow cannot turn around either. Bazaar's checkout page experiment in April was like this, and you will open it as an A/B test in lesson 42. But most of the time you cannot run an experiment; you have only observational data. Then what you do is think through the alternative explanations one by one and test as much as the data allows. First, match each of four claims with its most likely alternative explanation:
For each claim, which is the most likely alternative explanation?
For each row, pick its match from the list, then check.
Now let's go back to Bazaar. In the previous lesson you found r = 0.80 between ad spend and visitors, and in the scatter plot you saw weekend days gathering at the top. Weekend is a confounder candidate: on weekends the marketing team may spend more on ads, and people may browse the internet more on weekends anyway. Let's draw the situation as an arrow diagram:
The purple arrows show the two effects of the confounder; the dashed arrow is our real question: do ads bring visitors? If weekend raises both, part of the r = 0.80 we see across all days may come only from the information that "weekend days are high in both ads and visitors".
How do you test this? The idea is simple: hold the confounder fixed. If weekend creates the relationship, then when you look only at weekdays (where there is no weekend effect), the relationship should disappear or become much weaker. The same holds for weekend days alone. So you split the data into the groups of the confounder and look at the relationship again inside each group. The for name, group in df.groupby(...) loop you saw in lesson 28 does this for each group one by one:
import pandas as pd m = pd.read_csv("marketing.csv") print("All days r:", round(m["ad_spend"].corr(m["visitors"]), 3)) print(m.groupby("weekend")[["ad_spend", "visitors"]].mean().round(0)) for name, group in m.groupby("weekend"): r = round(group["ad_spend"].corr(group["visitors"]), 3) print("weekend =", name, "| days:", len(group), "| r:", r)
OutputAll days r: 0.797
ad_spend visitors
weekend
0 146.0 1372.0
1 184.0 1664.0
weekend = 0 | days: 129 | r: 0.89
weekend = 1 | days: 52 | r: 0.939The first table confirms the two arrows of the confounder: on weekends the average daily ad spend is $184 and on weekdays $146; visitors are 1,664 and 1,372. Weekend really does raise both. But look at the last two lines: within the 129 weekdays r = 0.89, and within the 52 weekend days r = 0.94. The relationship exists inside both groups, and it is even stronger than what we saw across all days.
What does this mean? Weekend cannot be the only explanation of the ad and visitor relationship: even with weekend held fixed, that is, among only weekdays or among only weekend days, the days with more ads are the days with more visitors. Let's correct a common mistake here: thinking "if there is a confounder, the relationship is completely false" is wrong. A confounder can create a relationship entirely (ice cream and drowning), but most of the time it only changes its size. Weekend probably makes the effect of ads look somewhat larger than it is; to say with a number how much larger, you need regression, which you will do in lesson 39.
Try the same test yourself with another confounder candidate. The ad campaign ended in May (lesson 10); maybe the time before and after May are two separate worlds. Run the cell as it is, then change the group line:
Try it now· not graded; doesn't affect progress
When you split by period, the table changes: in January–April daily ad spend is $224 and in May–June it is $25; visitors are 1,553 and 1,264. The within-group r values are 0.74 and 0.40: both are smaller than 0.80 for all days. So part of the 0.80 comes from the large gap between "four months with plenty of ads" and "two months with ads cut". But the relationship is not zero inside the periods either. For both confounder candidates you asked the same question and read the answer from the data.
Within weekdays r = 0.89, and within weekends r = 0.94. Can weekend be the only explanation of the relationship between ads and visitors?
Now let's move on to the product team's claim. First let's find two numbers ourselves. In lesson 7 you saw that the mean of a True/False column is the share of True values; the return rate is calculated this way. Next to the overall rate, let's put the category × device table with the pivot_table from lesson 8:
import pandas as pd o = pd.read_csv("orders.csv") o["returned"] = o["status"] == "returned" print(o.groupby("device")["returned"].mean().round(3)) print(o.pivot_table(index="category", columns="device", values="returned", aggfunc="mean").round(3))
Outputdevice
desktop 0.062
mobile 0.079
Name: returned, dtype: float64
device desktop mobile
category
Beauty 0.049 0.031
Books 0.023 0.014
Clothing 0.212 0.159
Electronics 0.037 0.021
Home & Living 0.041 0.024The first table confirms the product team's numbers: 7.9% returns on mobile and 6.2% on desktop. Read the second table row by row: in Beauty mobile is 3.1% and desktop 4.9%; in Books 1.4% and 2.3%; in Clothing 15.9% and 21.2%; in Electronics 2.1% and 3.7%; in Home & Living 2.4% and 4.1%. In each of the five categories the mobile return rate is lower. In total it is higher. At first glance this looks impossible.
In each of the five categories the mobile return rate is lower than desktop. How can the mobile rate be higher in total?
This situation is called Simpson's paradox: a relationship that shows one direction inside each of the groups shows the opposite direction when the groups are combined. Although the name contains "paradox", there is no contradiction; below you will see the reason with numbers. A similar case has been seen in a university's admission data: in total, one group had a low admission rate, but in most departments that group had a higher rate; that group had applied more to the departments with low admission rates.
Build the table yourself. Run it as it is first; then delete the # at the start of the crosstab line and look at how each device's orders are spread across categories:
Try it now· not graded; doesn't affect progress
The key to the paradox is in the last line of the cell. In lesson 8, normalize="columns" divided each column by its own total; here it gives how each device's orders are spread across categories, that is, the device's category mix:
import pandas as pd o = pd.read_csv("orders.csv") print(pd.crosstab(o["category"], o["device"], normalize="columns").round(3))
Outputdevice desktop mobile
category
Beauty 0.111 0.188
Books 0.119 0.141
Clothing 0.141 0.415
Electronics 0.295 0.091
Home & Living 0.333 0.16541.5% of mobile orders are Clothing; on desktop this share is 14.1%. Clothing is by far the category with the highest return rate (between 16% and 21%; the others are below 5%). Desktop mostly sells Electronics and Home & Living (29.5% and 33.3%), and returns are very low in both. The overall rate measures this: "which categories do this device's orders come from, and how high are returns in those categories?" The mobile total is high because its basket is full of Clothing; it says nothing about the mobile experience being bad.
The weighted mean you saw in lesson 13 appears here again. A device's overall return rate is the weighted mean of the category rates, weighted by that device's category shares: mobile's rates with mobile's mix, desktop's rates with desktop's mix. The two overall rates are calculated with two different sets of weights. This is why it is wrong to think "the overall rate is a kind of average of the subgroup rates, so the overall must say what the subgroups say": an average shifts with its weights.
The solution comes from here too: compare the two devices with the same weights. This is called standardization: combining the subgroup rates of two groups with the same subgroup weights to remove the difference in composition. The question becomes: "If mobile's orders had the same category mix as desktop's, what would mobile's return rate be?" Follow the calculation line by line; watch how total builds up in the variable boxes:
Run the code line by line: see which line runs next, the variable boxes and the output.
mobile_rate = [0.021, 0.024, 0.159, 0.014, 0.031] desktop_share = [0.295, 0.333, 0.141, 0.119, 0.111] total = 0 for rate, share in zip(mobile_rate, desktop_share): part = rate * share total = total + part print("Mobile, with desktop mix:", round(total, 3)) print("Desktop's own rate: 0.062")
The largest of the five products comes from Clothing (0.159 × 0.141 = 0.022), but Clothing's weight is now 14.1%, not 41.5%. The result is 0.042: with the desktop mix, mobile's return rate is 4.2%, below desktop's 6.2%. When the mix is equalized, the order reversed and became consistent with what the category table says.
Let's do the same calculation with pandas, using unrounded rates. np.average(values, weights=weights) from lesson 13 is made for exactly this job:
import numpy as np import pandas as pd o = pd.read_csv("orders.csv") o["returned"] = o["status"] == "returned" rate = o.pivot_table(index="category", columns="device", values="returned", aggfunc="mean") share = pd.crosstab(o["category"], o["device"], normalize="columns") mobile_std = np.average(rate["mobile"], weights=share["desktop"]) desktop_std = np.average(rate["desktop"], weights=share["desktop"]) print("Mobile, with desktop mix:", round(mobile_std, 3)) print("Desktop, with its own mix:", round(desktop_std, 3)) desktop_total = o.loc[o["device"] == "desktop", "returned"].mean() print("Check, desktop overall rate:", round(desktop_total, 3))
OutputMobile, with desktop mix: 0.042
Desktop, with its own mix: 0.062
Check, desktop overall rate: 0.062The last line is a sanity check: when you weight desktop's rates with its own mix, desktop's overall rate (0.062) comes back. So standardization gives both devices desktop's basket and asks "which one gets more returns on this basket?" The answer: desktop.
Why did we choose desktop's mix as the weights? The choice is a yardstick; there is no single correct choice. You could also have chosen mobile's mix, or equal weights for the five categories. What matters is that both sides are compared with the same weights. Change the weights below and look at the standardized rates of the two devices:
Change the weights: whichever mix you compare with, is mobile or desktop lower?
Pick a value; predict the output first, then look.
1import numpy as np2mix = "desktop"3# category order: Electronics, Home & Living, Clothing, Books, Beauty4returns_mobile = np.array([1, 2, 34, 1, 3])5orders_mobile = np.array([47, 85, 214, 73, 97])6returns_desktop = np.array([4, 5, 11, 1, 2])7orders_desktop = np.array([109, 123, 52, 44, 41])8rate_mobile = returns_mobile / orders_mobile9rate_desktop = returns_desktop / orders_desktop10if mix == "desktop":11 w = orders_desktop / orders_desktop.sum()12elif mix == "mobile":13 w = orders_mobile / orders_mobile.sum()14else:15 w = np.array([1, 1, 1, 1, 1]) / 516print("Mix:", mix)17print(f"Mobile (standardized): {np.average(rate_mobile, weights=w):.3f}")18print(f"Desktop (standardized): {np.average(rate_desktop, weights=w):.3f}")
Mix: desktop Mobile (standardized): 0.042 Desktop (standardized): 0.062
Faded lines didn't run with this value. With the desktop mix, mobile is 0.042 and desktop 0.062; with the mobile mix, 0.079 and 0.110; with equal weights, 0.050 and 0.072. The numbers change with the chosen mix, but in all three choices mobile is lower. With the mobile mix, desktop's rate rises to 0.110: if desktop also sold with mobile's Clothing-heavy basket, its returns would rise a lot.
Simpson's paradox does not appear only in e-commerce; it can appear anywhere the groups have different compositions. Think of the recovery rates of two hospitals in a city for one operation (fictional sample data). Patients are classified before the operation as "mild" and "severe":
import pandas as pd h = pd.DataFrame({ "hospital": ["A", "A", "B", "B"], "condition": ["mild", "severe", "mild", "severe"], "patients": [100, 400, 400, 100], "recovered": [95, 300, 370, 60], }) h["rate"] = h["recovered"] / h["patients"] print(h.pivot_table(index="condition", columns="hospital", values="rate").round(3)) total = h.groupby("hospital")[["patients", "recovered"]].sum() print((total["recovered"] / total["patients"]).round(3))
Outputhospital A B
condition
mild 0.95 0.925
severe 0.75 0.600
hospital
A 0.79
B 0.86
dtype: float64For mild patients A has 95% and B 92.5%; for severe patients A has 75% and B 60%. A is more successful in both groups. In total, B is ahead: 86% against 79%. The reason is the same: composition. 400 of A's 500 patients are severe, and 400 of B's are mild. Because the recovery rate of severe patients is low everywhere, the hospital that accepts severe patients, A, has its overall rate pulled down. Looking at the overall rate and saying "B is the better hospital" would punish the hospital that accepts severe patients. We also did the total carefully: first we added up the patient and recovered counts, then divided. Taking the plain average of the four rates would repeat the mistake from lesson 13.
A local newspaper has received the data of these two hospitals and wants to publish the headline "Hospital B is more successful: 86% recover, against 79% at A." The editor asks you for advice.
Pick an option and see what happens. There are no points; you can try the other options too.
The third option of the scenario shows the last misconception of the lesson: the idea that "more data solves the confounder". A large sample reduces the effect of chance (the third explanation), but it does not remove the confounder. In data ten times larger, severe patients still go to A and mild patients to B, and the overall rates tell the same wrong story, in an even more confident voice. Two things solve a confounder: random assignment, or measuring the confounder and controlling for it inside the groups (or in a model).
Let's turn all the tools of this lesson into one habit. When you see a relationship in observational data, ask three questions before you write a cause-and-effect sentence:
1. What else could be affecting both? (confounder: weekend, category, the patient's condition)
2. Could the direction be reversed? (sick people go to the hospital; people who sleep less drink coffee)
3. Who did the data come from, and how? (selection, chance in a small sample)
And use one of two solutions. Either design an experiment with random assignment (the A/B test in lesson 42), or measure and control the confounder: look inside the groups, standardize, or, as you will see in lesson 39, add the confounder to a regression model. When you write the result, fit the language to the data: from observational data you can say "mobile users return more often" (a relationship); you cannot say "the mobile experience increases returns" (a cause).
Put the steps of an analysis in the right order:
Put the steps in the right order when testing a relationship claim in observational data.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Let's return to the product team's sentence: "Returns are 7.9% on mobile and 6.2% on desktop; the mobile experience is bad and increases returns." The first half is a correct observation. The data does not support the second half: in every category the mobile return rate is lower, and with the same category mix mobile is 4.2% and desktop 6.2%. The difference in total comes from 41.5% of mobile orders being Clothing. This does not prove that the mobile experience is good; it only shows that the claim "the mobile experience increases returns" has no support in this data. The situation is similar for ads: the relationship stays when weekend is held fixed, but we have not yet said how much the ads affect visitors. In the next lesson you will turn this "how much" into a number with regression; in lesson 39 you will add the confounder to the model.
Not every split table hides a Simpson's paradox. Let's ask the same question for the cancellation rate:
import pandas as pd o = pd.read_csv("orders.csv") o["canceled"] = o["status"] == "canceled" print(o.groupby("device")["canceled"].mean().round(3)) print(o.pivot_table(index="category", columns="device", values="canceled", aggfunc="mean").round(3))
Outputdevice
desktop 0.041
mobile 0.037
Name: canceled, dtype: float64
device desktop mobile
category
Beauty 0.098 0.052
Books 0.091 0.041
Clothing 0.019 0.033
Electronics 0.028 0.000
Home & Living 0.024 0.047In total, desktop's cancellation rate is slightly higher (4.1% and 3.7%). Across categories the direction is mixed: desktop is higher in Beauty, Books, and Electronics, and mobile is higher in Clothing and Home & Living. For Simpson's paradox, all groups must point in the same direction while the total points the opposite way; there is no such table here. Also, these rates rest on very small counts (in Electronics there are no cancellations among 47 mobile orders); some of the category-by-category differences may come from chance.
Let's standardize the two hospitals to the same patient mix, half mild and half severe:
import numpy np
mild = {: 95 / 100, : 370 / 400}
severe = {: 300 / 400, : 60 / 100}
mix = [0.5, 0.5]
name [, ]:
std = np.average([mild[name], severe[name]], weights=mix)
(name, , (std, 3))Weighting each group with its own mix when standardizing. This fixes nothing; it gives back each device's overall rate:
import numpy as np import pandas as pd o = pd.read_csv("orders.csv") o["returned"] = o["status"] == "returned" rate = o.pivot_table(index="category", columns="device", values="returned", aggfunc="mean") share = pd.crosstab(o["category"], o["device"], normalize="columns") mobile_own = np.average(rate["mobile"], weights=share["mobile"]) desktop_own = np.average(rate["desktop"], weights=share["desktop"]) mobile_common = np.average(rate["mobile"], weights=share["desktop"]) print("Mobile, with its own mix:", round(mobile_own, 3)) print("Desktop, with its own mix:", round(desktop_own, 3)) print("Mobile, with desktop mix:", round(mobile_common, 3))
OutputMobile, with its own mix: 0.079
Desktop, with its own mix: 0.062
Mobile, with desktop mix: 0.042Next lesson: you will use simple linear regression to turn "how many more visitors come, on average, when ad spend goes up" into a number.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputA standardized recovery rate: 0.85
B standardized recovery rate: 0.762With the same mix, A gets 85% and B gets 76.2%. The order in the overall rates (B 86%, A 79%) reversed and became consistent with what the within-group table says.
The first two lines are the overall rates themselves (0.079 and 0.062): the difference in composition is still inside them. The whole idea of standardization is to combine both sides with the same weights; the third line does this.