…
…
Statistics and Data Analysis Fundamentals · Lesson 23 / 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.
At Bazaar, 64 of 885 orders were returned, about 7.2%. The logistics team has two questions: "What is the chance that a courier carrying five packages gets at least one return?" and "On how many days does a courier who delivers 20 packages a day come back with three or more returns?" In this unit you will learn to measure how much chance moves results. In the next unit we will use that measure to test claims.
By the end of this lesson you will give logistics two answers, and you will produce both with your own code:
| Question | Answer | How |
|---|---|---|
| At least one return among five packages | ≈ 0.31 | Complement: 1 − (1 − 0.072)⁵; check with a simulation |
| Share of 20-package days with 3 or more returns | ≈ 17% | Simulation of 10,000 days |
Behind the second answer there is a distribution: how many returns a 20-package day can bring, and how often each number appears. This is the distribution you will produce by simulation:
days · Bazaar orders.csv return rate, simulated (fictional sample data)
| — | number of days |
|---|---|
| 0 | 2336 |
| 1 | 3428 |
| 2 | 2535 |
In this lesson you will:
Probability theory began in the 17th century with a gambling question: if a dice game is stopped halfway, how do you split the money on the table fairly? Today the same thinking works in insurance prices, weather forecasts, and a store's expected returns.
First, let's make the word "probability" something we can talk about with data. The probability of an event is the share of times the event happens when the same situation is repeated many times. It is always between 0 and 1: 0 means "never happens" and 1 means "happens every time". You can also write it as a percent: 0.072 and 7.2% are the same thing.
In data analysis we usually estimate a probability from the observed proportion. If 64 of 885 orders were returned, the probability that a randomly chosen order is a return is about 64 / 885 = 0.0723. This is called the relative frequency: the number of times an event was seen divided by the total number of trials. Remember from lesson 7: in pandas this is the mean of a logical condition, because True counts as 1 and False counts as 0.
Now logistics' first question: at least one of five packages is returned. Counting "at least one" directly is tiring: you would need exactly one return, exactly two, ... exactly five, and add each one up. The opposite is much simpler: "no returns at all". The probability that an event does not happen is called the complement, and it is always 1 minus the probability that it happens. "At least one return" and "no returns" are complements of each other: if one does not happen, the other does, and they cannot happen together.
The chance that one package is not returned is 1 − 0.072 = 0.928. For none of the five packages to be returned, the first, the second, ... and the fifth must all stay. If the packages do not affect each other, we multiply these shares: 0.928⁵. Here we made an assumption: the packages are independent, which means that one package being returned does not change the chance of another. This is not always true. The same customer might return all five packages in one decision, and then the calculation looks better than reality. Knowing the assumption means knowing how seriously to take the result.
import pandas as pd s = pd.read_csv("orders.csv") p = (s["status"] == "returned").mean() none_returned = (1 - p) ** 5 print("Chance one package is returned:", round(p, 4)) print("No returns in five packages:", round(none_returned, 3)) print("At least one return in five packages:", round(1 - none_returned, 3))
OutputChance one package is returned: 0.0723
No returns in five packages: 0.687
At least one return in five packages: 0.313If you round the probability to 0.072, the result is 0.312. Both mean "close to one courier in three". Before you see the calculation, answer this question with your intuition:
There are five packages, and each has a 7.2% chance of being returned. About how likely is it that at least one is returned?
Adding probabilities is a tempting shortcut, but it is wrong. When you increase the number of packages, you see why: for 20 packages, 20 × 0.072 = 1.44, and no probability can be larger than 1. With the complement, the "no returns" share gets a little smaller with every package but never goes below zero, and "at least one" gets close to 1 but never passes it. Change the number of packages and watch:
How does the probability of "at least one return" change as the number of packages grows?
Pick a value; predict the output first, then look.
1n = 52p_return = 0.0723none_returned = (1 - p_return) ** n4print("No returns:", round(none_returned, 3))5print("At least one return:", round(1 - none_returned, 3))
No returns: 0.688 At least one return: 0.312
Faded lines didn't run with this value. A probability of 7% for one package passes one half with 10 packages and reaches almost certainty (0.976) with 50 packages, but it never goes above 1. The adding way would give 3.6 for 50 packages.
We solved the five-package question with a formula because the formula was short. But for the second question ("3 or more returns among 20 packages") the complement is not enough: you would need to find the probability of days with 0, 1, and 2 returns separately. When a question gets a little more complicated (for example, "how many bad days in a month"), the formula quickly gets hard. A simulation opens another way: imitate the process that involves chance on the computer thousands of times and count the results. You do not need to know a formula; you only need to describe the process correctly.
The raw material of the imitation is random numbers. NumPy's random number generator is set up like this: rng = np.random.default_rng(42). rng.random(5) gives five numbers between 0 and 1; the chance that a number falls in any part between 0 and 1 equals the width of that part. So the chance that a number is smaller than 0.072 is exactly 0.072. This is how we imitate whether a package is returned: if the number is below 0.072, it is a return; if not, it is delivered.
The 42 in the brackets is a seed. The random numbers of a computer actually come from a chain of calculations, and the seed is the starting point of the chain. A generator set up with the same seed gives the same numbers in the same order every time you run it. This makes your results repeatable: a simulation that gives 0.31 on your computer gives 0.31 on your friend's computer too. A seed is like a save file in a game: everyone who starts from the same save sees the same level.
import numpy as np rng = np.random.default_rng(42) numbers = rng.random(5) print(numbers.round(3)) print(numbers < 0.072)
Output[0.774 0.439 0.859 0.697 0.094]
[False False False False False]rng.random(5) returns a NumPy array. An array is similar to a pandas column: a comparison such as numbers < 0.072 is applied to each element separately and gives an array of True/False. None of the first five numbers is below 0.072: there is no return in this delivery. The fifth number, 0.094, is close to the limit, but it is still not below it.
Follow step by step how this decision is made inside, with plain Python. Think of the list below as five numbers that came from a random generator; the loop goes through the packages one by one and counts the returns. After you watch it, change the numbers in the list (for example, make all of them larger than 0.5, or put in two values of 0.01) and see how the result changes.
Run the code line by line: see which line runs next, the variable boxes and the output.
numbers = [0.31, 0.05, 0.77, 0.02, 0.64] p_return = 0.072 returns = 0 for x in numbers: if x < p_return: returns = returns + 1 print(x, "-> return") else: print(x, "-> delivered") print("Number of returns:", returns) print("Is there at least one return?", returns >= 1)
Imitating one delivery teaches nothing; it is a single result. The power is in repeating: we imitate 10,000 deliveries and count in how many of them there is at least one return. For this we write rng.random((10_000, 5)): the pair in the brackets is the number of (rows, columns), and it produces a table of numbers with 10,000 rows and 5 columns. Each row is a delivery and each column is a package. < 0.072 turns the table into a table of True/False. Then two new tools: any(axis=1) asks each row "is there at least one True?" (axis=1 means "along the row"), and mean() gives the mean of these answers, which is the proportion.
import numpy as np rng = np.random.default_rng(42) packages = rng.random((10_000, 5)) < 0.072 print(packages.shape) print(packages[:6].astype(int)) at_least_one = packages.any(axis=1) print(at_least_one[:6]) print("Estimate:", round(at_least_one.mean(), 3))
Output(10000, 5)
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 1 0 0]
[0 0 0 0 0]
[0 0 1 0 0]]
[False False False True False True]
Estimate: 0.31When you read this code, shape gives the size of the table: 10,000 rows and 5 columns. [:6] takes the first six deliveries (like slicing in lists), and astype(int) turns True/False into 1/0, which is easier to read. In the fourth and sixth deliveries the third package was returned, and any(axis=1) wrote True for those two rows. The last line is the share of the 10,000 deliveries that have at least one return: 0.31. This is almost the same as the 0.312 that the formula gave.
Run the simulation yourself. First as it is, then with trials = 10 and trials = 100_000:
Try it now· not graded; doesn't affect progress
With 10 trials we found 0.20, and with 10,000 trials we found 0.31. Which one is "right"? Both were found with the same method; the difference is the number of trials. To see this in a systematic way, let's run one big simulation and look at the proportion of the first 10, the first 100, ... deliveries:
import numpy as np rng = np.random.default_rng(42) packages = rng.random((100_000, 5)) < 0.072 for n in [10, 100, 1_000, 10_000, 100_000]: print(n, round(packages[:n].any(axis=1).mean(), 3))
Output10 0.2
100 0.28
1000 0.301
10000 0.31
100000 0.311Only two of the first ten deliveries have a return: 0.20. In this short series we do not see the real probability, but a swing of chance. With 100 deliveries it is 0.28, with 1,000 it is 0.301, with 10,000 it is 0.31, and with 100,000 it is 0.311: the proportion gets closer and closer to the formula's 0.312 and hardly leaves it. This is why we use large numbers of trials, such as 10,000, in simulations.
The name of this behavior is the law of large numbers: the more often you repeat an experiment, the closer the observed proportion gets to the true probability. Let's see it with coin tosses (an example outside the case). rng.integers(0, 2, size=10_000) produces 0 or 1; we count 1 as heads. cumsum() gives the cumulative sum (the number of heads in the first n tosses), and np.arange(1, 10_001) gives the numbers from 1 to 10,000; when you divide one by the other, you get "the share of heads so far" at every moment.
import numpy as np rng = np.random.default_rng(42) tosses = rng.integers(0, 2, size=10_000) share = tosses.cumsum() / np.arange(1, 10_001) print([round(float(share[n - 1]), 3) for n in (10, 100, 1000, 10_000)])
Output[0.4, 0.52, 0.509, 0.494]After ten tosses the share of heads is 0.4: four of the ten tosses are heads. This is not surprising; with ten tosses it is common to see 3 or 7 heads. After 100 tosses it is 0.52, after 1,000 it is 0.509, and after 10,000 it is 0.494. The share settles around 0.5.
The law has a part that is often misread: the law is about the long run, not about the next toss. A coin does not remember its past; each toss is independent of the earlier ones. The share gets close to 0.5 not because an earlier deviation is "made up for", but because in thousands of new tosses the weight of the first few tosses melts away.
A fair coin came up tails five times in a row. What is the probability of heads on the sixth toss?
The name of this mistake is the gambler's fallacy: believing that a short series must "balance out". It applies to couriers too: a courier who has had no returns for three days is not "due" for a return today; every day has the same chance.
Now logistics' second question: on how many days does a courier who delivers 20 packages a day come back with 3 or more returns? We are no longer asking "is there at least one?" but "how many?" We build the same table, but this time each row is a day and each column is one of that day's packages: 10,000 rows and 20 columns. Along the row we use sum(axis=1) instead of any; because True counts as 1, it gives the number of returns for each day.
The values that the number of successes takes in n independent trials, each with the same probability of success, and how often it takes them, is called the binomial distribution. Here "success" only means "the event we count"; a return is not a good thing, but it is the event we count.
import numpy as np import pandas as pd rng = np.random.default_rng(42) days = rng.random((10_000, 20)) < 0.072 k = days.sum(axis=1) print(pd.Series(k).value_counts().sort_index()) print("Mean:", k.mean()) print("At least 3:", (k >= 3).mean(), "| none:", (k == 0).mean())
Output0 2336
1 3428
2 2535
3 1206
4 377
5 95
6 21
7 1
8 1
Name: count, dtype: int64
Mean: 1.424
At least 3: 0.1701 | none: 0.2336k is an array of 10,000 elements: the number of returns for each day. We made the frequency table with value_counts().sort_index(), as in lesson 11 (we first turned the array into a column with pd.Series). Let's read it: of the 10,000 days, 2,336 have no returns, the most common value is 1 return (3,428 days), and 3 or more returns happened on 1,206 + 377 + 95 + 21 + 1 + 1 = 1,701 days, which is 0.170. The answer for logistics: on about 17% of 20-package days, the courier comes back with three or more returns; if there are 22 working days in a month, that means 3 to 4 days a month.
The mean is 1.424 returns; this is very close to 20 × 0.072 = 1.44. It is not a coincidence that the mean is "number of trials × probability": each package brings 0.072 returns on average, so 20 packages bring 1.44. Do not confuse this number with a probability: 1.44 is the expected number of returns in a day, not the probability of an event. A probability cannot pass 1, but an average count can.
There is also an off-by-one warning: "at least 3" means "3 and above", and the code is k >= 3. If you write k > 3, you leave 3 out and lose 1,206 days; the result is 0.05 instead of 0.17. When you turn words into code, check the equals sign every time.
Produce the distribution and its histogram yourself. After you run it, change "at least 3" to "at least 4":
Try it now· not graded; doesn't affect progress
Different questions are read from the same array with different code. Match each question with its code:
k is the array that holds the number of returns for each day. Which code answers each question?
For each row, pick its match from the list, then check.
Building a table with 20 columns and summing the rows shows clearly what is happening, so we did that first. But when the process is exactly binomial, NumPy has a shortcut: rng.binomial(20, 0.072, size=10_000). The first number is the number of trials (packages), the second is the probability in each trial, and size is how many times to repeat (days). It gives the number of returns for each day directly.
import numpy as np rng = np.random.default_rng(42) k = rng.binomial(20, 0.072, size=10_000) print(k[:10]) print("Mean:", k.mean()) print("At least 3:", (k >= 3).mean())
Output[2 1 3 2 0 4 2 2 0 1]
Mean: 1.4299
At least 3: 0.1668The result is 0.1668: very close to the 0.1701 that we found with the table, but not the same. Why? The two methods use the numbers from the generator in different ways; even if they start from the same seed, they produce different "random" days. Both are estimates of the same true probability, and the difference between them is the share of chance. When you increase the number of trials, both get close to the same number.
When is the shortcut right? When three conditions are met: the number of trials is fixed (20 packages), the trials are independent of each other, and the probability is the same in each trial. If one of them is broken (for example, Clothing packages have a much higher chance of being returned than Books, and the mix of packages changes from day to day), you go back to the table method and describe the process by hand. Put the lines of the shortcut in the right order:
Put the lines in order for the code that simulates 10,000 days of 20 packages with the binomial shortcut and prints the share of "at least 3 returns".
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The same thinking works for every "how many successes in n trials" question outside returns. A basketball player who makes 70% of free throws takes 10 shots in a game. What is the probability that she makes at least 8 of them? Each shot is a trial (10 columns), and each game is a row:
import numpy as np rng = np.random.default_rng(42) shots = rng.random((10_000, 10)) < 0.7 made = shots.sum(axis=1) print("At least 8 made:", (made >= 8).mean()) print("Fewer than 8:", (made < 8).mean())
OutputAt least 8 made: 0.3808
Fewer than 8: 0.6192A 70% player makes at least 8 of 10 shots in only 38% of games. Read the other way around: in 6 of every 10 games she stays below 8. "70% accuracy" is the proportion in the long run; in a single game it is normal to see 5, 6, or 9 made shots. Now make a decision with this knowledge:
A coach removes a player from the squad if she does not make at least 8 of 10 free throws in a game. The player's accuracy, known from hundreds of practice shots, is 70%. In this game she made 6. What do you tell the coach?
Pick an option and see what happens. There are no points; you can try the other options too.
This is the power of simulation: without knowing a formula, by describing the process, you could answer "how often does this result happen by chance?" The central question of the next unit will be exactly this: is the difference we observed real, or is it the usual swing of chance?
A single 7.2% treats all packages the same. When we split by category, the probabilities are very different:
import pandas as pd s = pd.read_csv("orders.csv") s["returned"] = s["status"] == "returned" p = s.groupby("category")["returned"].mean() print(p.round(3)) print("At least one return in five Clothing packages:", round(1 - (1 - p["Clothing"]) ** 5, 3))
Outputcategory
Beauty 0.036
Books 0.017
Clothing 0.169
Electronics 0.032
Home & Living 0.034
Name: returned, dtype: float64
At least one return in five Clothing packages: 0.604The probability that a courier carrying five Clothing packages gets at least one return is 0.60, twice the 0.31 calculated with the overall proportion. When the assumption "the probability is the same for every package" breaks, you need a separate calculation for each category.
rng.integers(1, 7, size=(10_000, 2)) produces dice rolls from 1 to 6 (the upper limit 7 is not included); each row is a roll of two dice.
import numpy as np rng = np.random.default_rng(42) dice = rng.integers(1, 7, size=(10_000, 2)) print("Simulation:", (dice == 6).any(axis=1).mean()) (, (1 - (5 / 6) ** 2, 4))
Setting up the random generator again inside the loop:
import numpy as np returned = 0 for i in range(1_000): rng = np.random.default_rng(42) if rng.random() < 0.072: returned = returned + 1 print(returned / 1_000)
Output0.0Because the generator is set up from the start with the same seed in every round, the same first number comes in every round: 0.774. Since this number is not below 0.072, none of the 1,000 packages counts as a return, and the proportion is 0.0. The right way is to set up the generator once before the loop; then each round takes the next number in the chain, and the same code prints 0.071.
np.random.default_rng(42), set up once before the loop) and counts the results; by the law of large numbers the estimate settles at the true probability as the number of trials grows, while short series mislead.True/False table whose rows are summed, or with rng.binomial(n, p, size); an "at least k" question is read with (k >= k_count).mean().Next lesson: we will read how the probability changes when something is known (for example, that an order is Clothing) with a cross-tabulation.
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.
| 3 | 1206 |
|---|
| 4 | 377 |
|---|
| 5 | 95 |
|---|
| 6 | 21 |
|---|
| 7 | 1 |
|---|
| 8 | 1 |
|---|
OutputSimulation: 0.2981
Complement: 0.3056The chance of not getting a six on one die is 5/6; the chance of no six at all on two dice is (5/6)² = 0.694, and at least one six is 0.306. The simulation is close at 0.298; the difference is the share of chance.