…
…
Statistics and Data Analysis Fundamentals · Lesson 26 / 44 · Samples and the normal model
PreviewIn this lesson you will
stats.normYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The A/B test records show how many seconds each of 195 sessions spent on the checkout page. The product team wants to know how many payments take longer than 3 minutes and which checkout time should earn the "fast checkout" badge. Customer service comes with a question left over from the previous lesson: how far can the mean of a sample of 30 orders fall from the population mean, and can they answer it without running thousands of simulations every time?
By the end of the lesson you will be able to give both teams a one-page answer. The table below summarizes the answers; you will calculate every row yourself during the lesson:
| Question | Method | Answer |
|---|---|---|
| What share of payments take longer than 180 seconds? | Normal model, compared with the data | Model 0.030, data 0.021 |
| Where is the cutoff for the fastest 10% of payments? | Percentile of the normal model | Model 72.4 s, data 74.0 s → badge "under 75 seconds" |
| How much does the mean of 30 orders typically move? | Standard error σ / √n | About $18.5 |
In this lesson you will:
stats.norm tools of the SciPy library to calculate the probability of an interval and a percentile.A continuous variable such as checkout time can take infinitely many values: 116 seconds, 116.3 seconds, 116.31 seconds... Because of this, the probability of one exact value is practically zero, and probabilities are calculated for intervals: "the probability of being between 100 and 130 seconds". A continuous distribution is described by a density curve. The probability of an interval is the area under the curve over that interval. The total area under the curve is 1, which means "100% of all payments".
The most common curve in statistics is the symmetric, bell-shaped normal distribution. Carl Friedrich Gauss used it in the early 19th century to model measurement errors in the positions of celestial bodies, so it is also called the Gaussian distribution. Only two numbers define a normal model: the mean μ (mu), which sets the center, and the standard deviation σ (sigma), which sets the width. Because the model is symmetric, the mean and the median are at the same point.
The most useful result of the normal model is the 68-95-99.7 rule: about 68% of the values fall within μ ± 1σ, about 95% within μ ± 2σ, and about 99.7% within μ ± 3σ. In lesson 14 you read the standard deviation as a "typical distance". This rule ties that distance to a concrete share. The rough rule from lesson 16 ("in a bell-shaped distribution most observations lie between z = −2 and 2") comes from here too.
Example 1 (case): checkout time. First we find the mean and standard deviation of the data and check whether the rule holds in the data. "Within ±1σ" means that the distance of the value from the mean (the absolute difference) is at most one standard deviation:
import pandas as pd sessions = pd.read_csv("sessions.csv") x = sessions["checkout_time_sec"].dropna() m, s = x.mean(), x.std() print(len(x), round(m, 1), round(s, 1)) print(round(((x - m).abs() <= s).mean(), 3)) print(round(((x - m).abs() <= 2 * s).mean(), 3)) print(round(((x - m).abs() <= 3 * s).mean(), 3))
Output195 116.3 34.3
0.662
0.959
1.0The 195 payments have a mean of 116.3 seconds and a standard deviation of 34.3 seconds. 66.2% of the payments fall between 82 and 150 seconds (±1σ), 95.9% fall between 47.7 and 184.9 seconds (±2σ), and all of them fall within ±3σ. These values are very close to the 68, 95, and 99.7 that the rule expects. In a data set of 195 observations, differences this small can come from chance. The normal model is a reasonable summary for this variable.
To find the probability of an interval under the model, you need the area under the curve. We do not calculate this by hand. SciPy, Python's scientific computing library, does it for us. The line from scipy import stats opens the statistics part of the library. stats.norm.cdf(z) gives the area to the left of z under the standard normal curve, which is "the probability of being less than z". The standard normal is the normal model with mean 0 and standard deviation 1. The z-score from lesson 16 (z = (x − μ) / σ) converts any normal value to this common unit. Predict first, then see the answer of the model:
If checkout times follow a normal model with a mean of 116 and a standard deviation of 34 seconds, about what percent of payments take between 48 and 184 seconds?
Now change one time value and watch how the z-score and the share below it change together:
As the checkout time (x) changes, how do the z-score and the share of payments shorter than it change?
Pick a value; predict the output first, then look.
1from scipy import stats2x = 1503mu, sigma = 116, 344z = (x - mu) / sigma5print("z =", round(z, 2))6print("Share shorter than this:", round(stats.norm.cdf(z), 3))
z = 1.0 Share shorter than this: 0.841
Faded lines didn't run with this value. The share below the mean (116) is exactly 0.5: the model is symmetric. From 82 to 150 is ±1σ: 0.841 − 0.159 ≈ 0.68. From 48 to 184 is ±2σ: 0.977 − 0.023 ≈ 0.95.
To see the same idea in a picture, we can draw the normal curve on top of the histogram. density=True puts the bar heights on the same scale as the curve (the total area of the bars becomes 1). stats.norm.pdf gives only the height of the curve, and here it is used only for drawing:
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats sessions = pd.read_csv("sessions.csv") x = sessions["checkout_time_sec"].dropna() fig, ax = plt.subplots() ax.hist(x, bins=15, density=True) points = np.linspace(0, 240, 200) ax.plot(points, stats.norm.pdf(points, x.mean(), x.std())) ax.set_title("Checkout time and the normal model") ax.set_xlabel("Checkout time (s)") print("Number of bars:", len(ax.patches))
OutputNumber of bars: 15The bars go up and down around the curve, but the overall shape is the same: one peak in the middle and two symmetric sides.
Not every data set is normally distributed. Applying the normal model without checking it is one of the most common mistakes. Let's run the same check on order amount. In lesson 16 you saw that the amount is strongly right-skewed (skewness 4.18).
Example 2 (case): two variables side by side. We calculate the same three shares for both variables and put them in one table next to the values the normal model expects:
import pandas as pd sessions = pd.read_csv("sessions.csv") orders = pd.read_csv("orders.csv") time_sec = sessions["checkout_time_sec"].dropna() amount = orders["amount"] time_share = [] amount_share = [] for k in [1, 2, 3]: time_share.append(((time_sec - time_sec.mean()).abs() <= k * time_sec.std()).mean()) amount_share.append(((amount - amount.mean()).abs() <= k * amount.std()).mean()) table = pd.DataFrame( {"checkout time": time_share, "amount": amount_share, "normal model": [0.683, 0.954, 0.997]}, index=["±1σ", "±2σ", "±3σ"], ) print(table.round(3)) print(round(amount.mean(), 1), round(amount.std(), 1))
Output checkout time amount normal model
±1σ 0.662 0.918 0.683
±2σ 0.959 0.963 0.954
±3σ 1.000 0.974 0.997
75.5 101.2The amount has a mean of $75.5 and a standard deviation of $101.2. The amount column is very different from the model. Instead of 68%, 91.8% of the values are within ±1σ: most orders are piled up near the mean (in fact below it). Outside ±3σ there are 2.6% of the orders instead of 0.3%: a few very large baskets form a long right tail. The model describes both the center and the tail wrongly.
Think for a moment: according to the normal model, what would be the probability that an order amount is below zero?
If we summarize the amount with a normal model that has a mean of $75.5 and a standard deviation of $101.2, how much probability does the model give to a negative amount (below $0)?
The model gives a 22.8% probability to negative amounts that do not exist. Here is the summary of the check: first, count the 68-95-99.7 shares in the data. If the shares are close to the expected values and the histogram has one peak and is symmetric, the model is a reasonable summary. If the shares are far off, or the histogram is skewed or has two peaks, the extreme probabilities calculated with the model will mislead you. In that case you work from the data (with proportions and percentiles). Match the four variables with the decision:
Is the normal model suitable for these four Bazaar variables?
For each row, pick its match from the list, then check.
cdf, sf, ppfIf the model is suitable, you can answer every question with its two parameters. stats.norm offers three basic functions, and all three take loc (the mean) and scale (the standard deviation):
| Function | What it gives | Checkout example |
|---|---|---|
stats.norm.cdf(x, loc, scale) | Probability of being less than x (area on the left) | Probability of taking less than 82 seconds |
stats.norm.sf(x, loc, scale) | Probability of being greater than x (area on the right, 1 − cdf) | Probability of taking more than 180 seconds |
stats.norm.ppf(q, loc, scale) | The value with area q on its left (a percentile) | The cutoff for the fastest 10% |
ppf is the inverse of the other two: cdf takes a time and gives a probability, while ppf takes a probability and gives a time. You can think of it as the model version of the quantile function from lesson 15.
Example 3 (case): the badge and 3 minutes. We answer the two questions first with the model and then directly from the data, and compare them. If the number from the model is close to the number from the data, you can trust the model. If not, you work with the data.
import pandas as pd from scipy import stats sessions = pd.read_csv("sessions.csv") x = sessions["checkout_time_sec"].dropna() mu, sigma = 116, 34 print("Model P(> 180):", round(stats.norm.sf(180, loc=mu, scale=sigma), 3)) print("Data P(> 180):", round((x > 180).mean(), 3)) print("Model 10% cutoff:", round(stats.norm.ppf(0.10, loc=mu, scale=sigma), 1)) print("Data 10% cutoff:", round(x.quantile(0.10), 1))
OutputModel P(> 180): 0.03
Data P(> 180): 0.021
Model 10% cutoff: 72.4
Data 10% cutoff: 74.0The model says that 3% of the payments take longer than 3 minutes. In the data this share is 2.1% (4 of the 195 payments). Both say "roughly one payment in 30 to 50". The cutoff for the fastest 10% is 72.4 seconds in the model and 74.0 seconds in the data. Our advice to the product team: let the badge be "under 75 seconds". It rewards roughly one payment in ten. The model is useful here for this reason: in a 2% tail of 195 observations there are only 4 payments, and one payment moves the share by half a percentage point. The model estimates the tail more smoothly, using two numbers that come from all the data.
Try it yourself. The cell does the model calculations. Add the lines that answer the same questions from the data:
Try it now· not graded; doesn't affect progress
Now let's go back to the question from customer service. In lesson 25 you drew thousands of samples of 30 from the population and plotted a histogram of their means. The order amount is strongly skewed, yet that histogram looked like a bell. This is not a coincidence.
The central limit theorem (CLT): whatever the shape of the population, the mean of random samples approaches a normal distribution as n grows. Pierre-Simon Laplace showed this result in the early 19th century. The theorem says nothing about single observations. It is only about the distribution of sample means.
Example 4 (case): how skewness melts away. For each n, we draw 10,000 random samples and look at the skewness of their means (from lesson 16: the skewness of a symmetric distribution is close to 0):
import numpy as np import pandas as pd x = pd.read_csv("orders.csv")["amount"].to_numpy() print("Single amounts:", round(pd.Series(x).skew(), 2)) rng = np.random.default_rng(42) for n in [5, 30, 100]: means = rng.choice(x, size=(10_000, n)).mean(axis=1) print("n =", n, "→ skewness of the means:", round(pd.Series(means).skew(), 2))
OutputSingle amounts: 4.18
n = 5 → skewness of the means: 1.84
n = 30 → skewness of the means: 0.79
n = 100 → skewness of the means: 0.39The skewness of the single amounts is 4.18. It drops to 1.84 for means of 5 orders, to 0.79 for means of 30, and to 0.39 for means of 100. Taking a mean softens extreme values: a basket of $899.90 enters a mean of 100 orders with a weight of only one percent.
There are two misunderstandings here. The first is "the CLT makes the data normal." It does not. The single amounts always keep their skewness of 4.18. What approaches a normal curve is the distribution of the means. The second is "n ≥ 30 is always enough." This is a common rule of thumb, but it depends on the shape of the population. For a variable this skewed, the skewness of the means of 30 is still 0.79. For a population close to symmetric even 10 can be enough, while for a very skewed population you may need 100.
We draw samples of 100 orders at Bazaar. When n = 100, which distribution approaches a normal curve?
Draw the three histograms side by side and see how the shape changes. Then change the numbers in the list:
Try it now· not graded; doesn't affect progress
The histograms do not only change shape, they also get narrower. We do not have to measure how much narrower by simulation every time. There is a formula. The standard deviation of the sample means is called the standard error (SE):
SE = σ / √n
Here σ is the standard deviation of the population and n is the sample size. At Bazaar we treat the 885 orders as the population. The standard deviation of a population is calculated by dividing by n, so we use the NumPy default (lesson 14): σ = $101.2. For n = 30, SE = 101.2 / √30 ≈ $18.5.
Example 5 (case): formula and simulation. Let's compare the formula with a simulation of 10,000 samples. We also count whether about 95% of the means fall within μ ± 2 SE, as the normal model says:
import numpy as np import pandas as pd x = pd.read_csv("orders.csv")["amount"].to_numpy() mu, sigma = x.mean(), x.std() rng = np.random.default_rng(42) for n in [30, 100]: means = rng.choice(x, size=(10_000, n)).mean(axis=1) se = sigma / np.sqrt(n) inside = (np.abs(means - mu) <= 2 * se).mean() print("n =", n, "| formula:", round(se, 1), "| simulation:", round(means.std(), 1), "| within ±2 SE:", round(inside, 3))
Outputn = 30 | formula: 18.5 | simulation: 18.5 | within ±2 SE: 0.958
n = 100 | formula: 10.1 | simulation: 10.2 | within ±2 SE: 0.955The formula and the experiment give the same result: for n = 30 both give 18.5, and for n = 100 they give 10.1 and 10.2. 95.8% of the means of 30 orders fall within ±2 standard errors (±$37) of the population mean. This is very close to the 95% of the normal model. So we can now tell customer service, without running 5,000 simulations: the mean of 30 orders typically differs from the population mean by $18.5, and rarely by more than $37.
The square root in the formula has an important consequence. Predict:
By what factor must you increase the sample size to cut the standard error in half?
Multiply n by four at each step and watch how the standard error changes:
How does the standard error shrink as the sample grows?
Pick a value; predict the output first, then look.
1n = 302sigma = 1013se = sigma / n ** 0.54print("Standard error: $" + str(round(se, 1)))
Standard error: $18.4
Faded lines didn't run with this value. At each step the sample becomes four times larger and the standard error is cut in half: 18.4 → 9.2 → 4.6 → 2.3 dollars. Precision does not grow in proportion to the data. Each halving costs four times more than the one before.
This is why in surveys, going from 400 people to 1,600 people cuts the error in half, but going from 1,600 to 6,400 gives the same gain at four times the cost. Do not confuse the standard error with the standard deviation. The standard deviation ($101) describes how much single orders are spread out. The standard error ($18.5) describes how much the mean of 30 orders moves. The first does not shrink as n grows. The second does.
So far we knew the standard deviation of the population because we had all 885 orders. In real life you have only one sample, and σ is unknown. The solution is simple: put the standard deviation of the sample itself (s, with ddof=1) in place of σ. SE ≈ s / √n.
Remember the first sample in lesson 25: the mean of 30 orders drawn with the same seed was $86.8. Let's calculate the standard error and the ±2 SE interval from this single sample:
import numpy as np import pandas as pd x = pd.read_csv("orders.csv")["amount"].to_numpy() rng = np.random.default_rng(42) sample = rng.choice(x, size=30) mean = sample.mean() s = sample.std(ddof=1) se = s / np.sqrt(30) print("Mean:", round(mean, 1), "| s:", round(s, 1), "| SE:", round(se, 1)) print("±2 SE:", round(mean - 2 * se, 1), "-", round(mean + 2 * se, 1))
OutputMean: 86.8 | s: 102.4 | SE: 18.7
±2 SE: 49.4 - 124.2The sentence to write to customer service: "In the sample of 30 orders, the mean basket is $86.8. The standard error is about $18.7, so this mean can easily be $37 away from the mean of the population. Instead of locking the campaign budget to $86.8, plan for something between $50 and $125." The SE calculated from a single sample (18.7) came out very close to the true value (18.5). The mean of the population ($75.5) is inside this interval. You will build this kind of interval and learn its correct interpretation in lesson 30, with the bootstrap. Put the lines in order:
Put the lines in order that calculate the standard error and the ±2 SE interval from a single sample (x and rng are ready).
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
One die is enough to see the CLT in its simplest form. The roll of a single die is uniformly distributed: each face from 1 to 6 is equally likely, there is no peak, and there is no bell at all. Now let's roll ten dice together, take their mean, and repeat this 10,000 times.
Example 6 (outside the case): dice. The standard deviation of a single die is √(35/12) ≈ 1.708. By the formula, the standard error of the mean of ten dice should be 1.708 / √10 ≈ 0.540:
import numpy as np rng = np.random.default_rng(42) rolls = rng.integers(1, 7, size=(10_000, 10)) means = rolls.mean(axis=1) print("Mean of the means:", round(means.mean(), 3)) print("Simulated SE:", round(means.std(), 3)) print("Formula SE:", round(np.sqrt(35 / 12) / np.sqrt(10), 3))
OutputMean of the means: 3.5
Simulated SE: 0.538
Formula SE: 0.54rng.integers(1, 7) produces an integer from 1 to 6 (the upper limit is not included). A single die is uniform, but the mean of ten dice gathers in a bell shape around 3.5. Its mean is 3.5 and its standard deviation is 0.538 (formula: 0.540). For the mean to be 1 or 6, all ten dice must show the same face, and this almost never happens. Change the number of dice and watch the shape of the histogram:
Try it now· not graded; doesn't affect progress
Counting the 68-95-99.7 shares is a quick check. A more systematic way is the normal probability plot (Q-Q plot): the sorted values of the data are compared with the values that the normal model expects at the same ranks. If the points lie on a straight line, the data are close to normal. stats.probplot(x) gives the numbers of this plot and the correlation (r) that shows how well the points fit the line. The closer r is to 1, the better the fit. You will see correlation in detail in lesson 36. For now, just read it as "close to 1 = close to the line".
import pandas as pd from scipy import stats sessions = pd.read_csv("sessions.csv") orders = pd.read_csv("orders.csv") result_time = stats.probplot(sessions["checkout_time_sec"].dropna()) result_amount = stats.probplot(orders["amount"]) print("Checkout time r:", round(result_time[1][2], 3)) print("Amount r:", round(result_amount[1][2], 3))
OutputCheckout time r: 0.999
Amount r: 0.761For checkout time the points lie almost perfectly on a line (0.999). For the amount they clearly depart from the line (0.761). The two checks give the same decision.
You can now say with one number how much a statistic moves by chance: the standard error. In unit 6 we will turn this into a decision tool: is an observed difference (for example, the difference between the conversion rates of two groups) larger than what chance can produce?
Between which two times do the middle 90% of the payments fall? Find the two percentiles that cut off the bottom 5% and the top 5% with ppf:
from scipy import stats mu, sigma = 116, 34 low = stats.norm.ppf(0.05, mu, sigma) high = stats.norm.ppf(0.95, mu, sigma) print(round(low, 1), round(high, 1)) print(round(stats.norm.cdf(high, mu, sigma) - stats.norm.cdf(low, mu, sigma), 2))
Output60.1 171.9
0.9The middle 90% of the payments take between 60 and 172 seconds. The two limits are 1.645 standard deviations below and above the mean.
Customer service wants the mean to move by typically at most $5. From the equation SE = σ / √n = 5, we get n = (σ / 5)²:
import pandas as pd x = pd.read_csv("orders.csv")["amount"].to_numpy() sigma = x.std() n = (sigma / 5) ** 2 print(round(sigma, 1), round(n))
Output101.2 409About 409 orders are needed, which is more than thirteen times the sample of 30. For a strongly skewed variable, precision is expensive.
Confusing the standard deviation with the standard error. The standard deviation describes how much single orders are spread out ($101). The standard error describes how much the sample mean moves (about $18.5 for n = 30). The sentence "The standard deviation is $101, so our estimate of the mean basket moves by ±$101" is wrong. The answer to "How precise is our estimate of the mean basket?" is the standard error, and it gets smaller as the sample grows.
stats.norm.cdf, sf, and ppf (scale is the standard deviation).Next lesson: We start asking whether chance can explain a result we observed: testing a claim with data.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.