…
…
Statistics and Data Analysis Fundamentals · Lesson 24 / 44 · Probability
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 overall return rate at Bazaar is 7.2%, but two numbers are going around in the meeting: "the return rate in Clothing is 17%" and "70% of returns are Clothing". The returns policy team wants to write a separate rule for Clothing without knowing which number says what. In the same week, orders flagged by the new fraud filter are being canceled as "surely fake".
By the end of this lesson you will build two tables yourself and write the right sentence under each. The first is a cross table of category and order status. The second is an imaginary crowd of 10,000 orders for the fraud filter:
| Question | Calculation | Answer |
|---|---|---|
| What share of Clothing orders is returned? | 45 / 266 | 0.169 |
| What share of returns is Clothing? | 45 / 64 | 0.703 |
| What share of flagged orders is really fake? | 95 / 590 | 0.161 |
In this lesson you will:
crosstab.In lesson 23 you defined probability as relative frequency: the probability that a randomly chosen order is returned is 64 / 885 = 0.072. Now someone gives you one more piece of information: the chosen order is Clothing. Does this change the probability? It does, because you no longer look at all orders, only at Clothing orders. The crowd you look at has become smaller.
First, let's make the cross table with margin totals (lesson 8):
import pandas as pd s = pd.read_csv("orders.csv") print(pd.crosstab(s["category"], s["status"], margins=True))
Outputstatus canceled completed returned All
category
Beauty 9 124 5 138
Books 7 108 2 117
Clothing 8 213 45 266
Electronics 3 148 5 156
Home & Living 7 194 7 208
All 34 787 64 885Read the Clothing row: 45 of the 266 Clothing orders are returned. The probability that an order is returned, when we know it is Clothing, is 45 / 266 = 0.169. This number is called a conditional probability, and it is written P(returned | Clothing). The vertical bar is read as "given" or "within": "the probability of a return, given Clothing", or in everyday words, "the share of returns within Clothing orders".
That is the whole definition: P(A | B) is the share of A among the cases where B happened. As a formula, P(A | B) = (count of A and B together) / (count of B). In pandas you do not need to remember the formula. There are two ways. The first is the conditional filtering from lesson 5: take the rows where B is true, then calculate the share there.
import pandas as pd s = pd.read_csv("orders.csv") clothing = s[s["category"] == "Clothing"] print(len(clothing), (clothing["status"] == "returned").sum()) print(round((clothing["status"] == "returned").mean(), 3))
Output266 45
0.169The second way does all categories in one step: give crosstab the argument normalize="index". Each row adds up to 1 within itself, so each cell becomes "the share of this column within this row". The returned column gives P(returned | category) for every category:
import pandas as pd s = pd.read_csv("orders.csv") share = pd.crosstab(s["category"], s["status"], normalize="index") print(share["returned"].round(3))
Outputcategory
Beauty 0.036
Books 0.017
Clothing 0.169
Electronics 0.032
Home & Living 0.034
Name: returned, dtype: float64The overall rate is 0.072, but it is 0.169 in Clothing, 0.032 in Electronics, and 0.017 in Books. Knowing the category really does change the probability of a return. Try it with your intuition first:
We picked a random order; the overall return probability is 0.072. Then we learned that the order is Clothing. What happens to the return probability?
One misunderstanding to avoid: conditional probability does not say "Clothing causes returns". It only says that returns are more common among Clothing orders. The table does not tell you the reason (wrong size, different color).
Now let's go to the second number from the meeting: "70% of returns are Clothing". This is also a conditional probability, but in the opposite direction: P(Clothing | returned). This time the crowd is the returns. 45 of the 64 returns are Clothing: 45 / 64 = 0.703.
Look at the table carefully: in both calculations the numerator is the same cell, 45. Only the denominator changes. For P(returned | Clothing) you divide 45 by the Clothing row total (266). For P(Clothing | returned) you divide it by the returned column total (64). In crosstab, this means normalize="columns": each column adds up to 1 within itself.
import pandas as pd s = pd.read_csv("orders.csv") column_share = pd.crosstab(s["category"], s["status"], normalize="columns") print(column_share["returned"].round(3))
Outputcategory
Beauty 0.078
Books 0.031
Clothing 0.703
Electronics 0.078
Home & Living 0.109
Name: returned, dtype: float64The two numbers answer two different questions. 0.169 describes the return risk of Clothing: the chance that a Clothing order comes back after you ship it. 0.703 describes where the returns come from: out of every 10 packages that reach the returns desk, 7 are Clothing. If the returns policy team thinks "most Clothing orders come back", they are wrong; only about one in six Clothing orders comes back. But if they want to reduce the workload of the returns warehouse, focusing on Clothing is right, because most returns come from there.
In the cell below we calculate the two directions with boolean columns. returned[clothing] means "the return flags in the Clothing rows"; its mean is the share of returns within Clothing. clothing[returned] is the opposite. Run it, then write "Beauty" instead of "Clothing":
Try it now· not graded; doesn't affect progress
For Beauty, the two directions give 0.036 and 0.078; again the same cell (5), two denominators (138 and 64). Now match four different questions with four calculations. One calculation is extra; it does not fit any question:
Which calculation answers each question? (Table: Clothing 266 orders, 45 returned; total 885 orders, 64 returned)
For each row, pick its match from the list, then check.
This is why it matters which event stands on which side of the bar. Keep the rule in one sentence: the event on the right of the bar is the denominator.
The most common form of direction confusion comes with the word "all". Let's look at Bazaar's A/B test sessions (sessions.csv, 1,000 sessions). Each row shows, as 0/1, whether the visitor added an item to the cart and whether they bought.
import pandas as pd o = pd.read_csv("sessions.csv") print(pd.crosstab(o["added_to_cart"], o["purchased"], margins=True)) cart = o["added_to_cart"] == 1 bought = o["purchased"] == 1 print("P(bought | cart):", bought[cart].mean().round(3)) print("P(cart | bought):", cart[bought].mean().round(3))
Outputpurchased 0 1 All
added_to_cart
0 665 0 665
1 230 105 335
All 895 105 1000
P(bought | cart): 0.313
P(cart | bought): 1.0All 105 sessions that bought had added to the cart first: buying without adding to the cart is not possible, so P(cart | bought) = 1.0. But only 105 of the 335 sessions that added to the cart bought: P(bought | cart) = 0.313. One is 100%, the other 31%. Predict:
In another store, 100% of the people who bought had added to the cart first. What share of the people who added to the cart bought?
Here is another question with the same conditional view: do new visitors buy more, or returning visitors?
import pandas as pd o = pd.read_csv("sessions.csv") print(o.groupby("new_visitor")["purchased"].mean().round(3))
Outputnew_visitor
0 0.117
1 0.089
Name: purchased, dtype: float64P(bought | returning visitor) = 0.117, P(bought | new visitor) = 0.089. Taking the mean with groupby is also a conditional probability: each group is a crowd, and the mean of the 0/1 column is the share inside that crowd (lesson 7).
Sometimes information does not change the probability at all. If knowing B does not change the probability of A, that is, if P(A | B) = P(A), then A and B are independent. In lesson 23 we treated five packages as independent: one package coming back did not change the probability of another. In data, exact equality is rare; in practice we ask "is the conditional rate very close to the overall rate?"
Let's look at device and returns. The overall return rate is 0.072; it is 0.062 on desktop and 0.079 on mobile. There seems to be a difference: mobile orders are returned more. But when we look inside each category, the picture reverses:
import pandas as pd s = pd.read_csv("orders.csv") s["returned"] = s["status"] == "returned" print(s.groupby("device")["returned"].mean().round(3)) print(s.groupby(["category", "device"])["returned"].mean().unstack().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.024In every category the return rate of mobile is lower than desktop; in total it is higher. How can that happen? 41.5% of mobile orders are Clothing, while on desktop this share is only 14.1%. Mobile moves up in total because it gets many more orders from the category with the highest return rate. Assuming that the conditional rate in the total also holds in every subgroup can be misleading. We will solve this reversal in detail in lesson 37. For now, the lesson is this: when you interpret a conditional rate, ask "what other variable could be getting in the way?"
Now we come to the most annoying part of the case. Bazaar started using a fraud filter. What we know:
The team says "the filter is 95% accurate, so if it raises an alarm, the order is 95% fake" and cancels the flagged orders. First, you predict:
1% of orders are fake. The filter raises an alarm for 95% of fake orders and a false alarm for 5% of real orders. About how likely is it that an order with an alarm is really fake?
The answer surprises most people. The way to see it without a formula is to turn the probabilities into counts: imagine an imaginary crowd of 10,000 orders and count who falls where. We call this a natural frequency table.
crowd = 10_000 fake = crowd * 0.01 caught = fake * 0.95 real = crowd - fake false_alarms = real * 0.05 print("Fake:", fake, "| alarm:", caught) print("Real:", real, "| alarm:", false_alarms) print("Total alarms:", caught + false_alarms) print("Fake share among alarms:", round(caught / (caught + false_alarms), 3))
OutputFake: 100.0 | alarm: 95.0
Real: 9900.0 | alarm: 495.0
Total alarms: 590.0
Fake share among alarms: 0.161Put into a table:
| Alarm | No alarm | Total | |
|---|---|---|---|
| Fake | 95 | 5 | 100 |
| Real | 495 | 9,405 | 9,900 |
| Total | 590 | 9,410 | 10,000 |
Look at the Alarm column: of the 590 alarms, 95 are fake and 495 are orders from real customers. P(fake | alarm) = 95 / 590 = 0.161. The filter is not bad; the problem is that real orders are far more numerous. Even a small part (5%) of the 9,900 real orders produces more alarms than a large part (95%) of the 100 fake ones. When you write 95% as P(alarm | fake) and 16% as P(fake | alarm), you see that this is again a direction confusion. It is a well-known mistake, and even courts have made it.
Let the filter stay the same, and change only the share of fake orders. How does the trust you can place in the alarms change?
The filter is the same (catches 95%, 5% false alarms). When the share of fake orders changes, how much of the alarms are really fake?
Pick a value; predict the output first, then look.
1crowd = 10_0002fake_rate = 0.013fake = crowd * fake_rate4caught = fake * 0.955false_alarms = (crowd - fake) * 0.056print("Number of alarms:", round(caught + false_alarms))7print("Of these, fake:", round(caught))8print("Fake share among alarms:", round(caught / (caught + false_alarms), 2))
Number of alarms: 590 Of these, fake: 95 Fake share among alarms: 0.16
Faded lines didn't run with this value. The filter did not change at all; only the base rate changed. When 1 in 1,000 orders is fake, 2% of the alarms are really fake; when 50% are fake, 95% are. The rarer the event, the larger the part of the alarms that is wrong.
The decision that follows is clear: the alarm of a rare event is not "certain"; it is the start of a second check. At Bazaar, instead of canceling flagged orders, sending them to a short verification (for example, a confirmation message to the customer) avoids losing a real customer in 5 out of every 6 alarms.
Conditional probability and direction confusion are not specific to shopping. Think of a school with 1,000 students (fictional sample data). 20% of the students are in a reading club. 60% of the club members and 30% of the students outside the club read at least one book a month. In natural frequencies: of 200 club members, 120 read and 80 do not; of 800 students outside the club, 240 read and 560 do not.
import pandas as pd table = pd.DataFrame( {"reads": [120, 240], "does_not_read": [80, 560]}, index=["in club", "not in club"], ) print(table) p_reads_club = table.loc["in club", "reads"] / table.loc["in club"].sum() p_club_reads = table.loc["in club", "reads"] / table["reads"].sum() print("P(reads | in club):", round(p_reads_club, 3)) print("P(in club | reads):", round(p_club_reads, 3))
Output reads does_not_read
in club 120 80
not in club 240 560
P(reads | in club): 0.6
P(in club | reads): 0.33360% of club members read, but only one third of the readers are in the club. Most readers are from outside the club, because students outside the club are four times as many. This time, build the table from the rates yourself; then change the club share:
Try it now· not graded; doesn't affect progress
When you set club_rate = 0.50, P(reads | in club) does not change (0.6), but P(in club | reads) goes from 0.333 to 0.667. Knowing one direction alone does not tell you the other; the other direction depends on the size of the groups (the base rate).
When you write a conditional probability in a report, the safest pattern is: "the share of … within …". If you say the denominator first, the direction does not get mixed up:
The numbers in parentheses also give the reader the size of the crowd; the denominator lesson from lesson 13 applies here too. Finally, put the code that fills the natural frequency table in the right order:
Put the lines that fill the natural frequency table in order: first the crowd, then the fake orders, the caught ones, the false alarms, and last the share.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
So far you have calculated probabilities from all of the data you have. But the 885 orders are also a sample; another six months would give slightly different rates. The next lesson measures how much a rate moves from sample to sample.
When you join the returned columns of the two crosstab results in one table, you see both the risk of each category and its share in the returns.
import pandas as pd s = pd.read_csv("orders.csv") risk = pd.crosstab(s["category"], s["status"], normalize="index")["returned"] share = pd.crosstab(s["category"], s["status"], normalize="columns")["returned"] print(pd.DataFrame({"P(returned | category)": risk, "P(category | returned)": share}).round(3))
Output P(returned | category) P(category | returned)
category
Beauty 0.036 0.078
Books 0.017 0.031
Clothing 0.169 0.703
Electronics 0.032 0.078
Home & Living 0.034 0.109The left column does not add up to 1 (each is a share within its own category); the right column adds up to 1 (the 64 returns are shared among five categories).
If the share of fake orders were 2 in 1,000, how reliable would the alarms of the same filter be?
crowd = 10_000 fake = crowd * 0.002 caught = fake * 0.95 false_alarms = (crowd - fake) * 0.05 (, (caught + false_alarms), , (caught)) (, (caught / (caught + false_alarms), 3))
Mixing up P(A | B) and P(B | A). The information "70% of returns are Clothing" does not mean "70% of Clothing orders are returned"; the return share of Clothing orders is 17%. In code, the same mistake is made by swapping two names:
Outputclothing[returned].mean() # 0.703: Clothing share within returns
returned[clothing].mean() # 0.169: return share within ClothingBefore you write a conditional probability, answer the question "within what?": the event on the right of the bar decides the crowd you count, that is, the denominator. The same mistake appears in the alarm question: "the filter catches 95% of fake orders" and "95% of the alarms are fake" are different sentences.
crosstab(..., normalize="index").Next lesson: The 885 orders you have are one sample; another sample would give another rate. You will see with a simulation how much a rate moves from sample to sample.
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.
OutputAlarms: 518 | fake: 19
Share: 0.037Only 19 of the 518 alarms are fake; about 26 of every 27 alarms are a real customer.