…
…
Statistics and Data Analysis Fundamentals · Lesson 25 / 44 · Samples and the normal model
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.
You have all 885 Bazaar orders in your hands, but in real life you often see only a part: one week of orders, a checklist of 30 orders, a survey of 300 people. Customer service found a mean basket of $86.78 in a sample of 30 orders and says, "Let's plan the campaign budget on this." In this lesson you will measure by simulation how far the mean of 30 orders can move.
By the end of the lesson you will give customer service the answer below and produce every number in it with your own code:
| Question | Answer |
|---|---|
| Mean of all orders | $75.53 (in this lesson we have the whole population) |
| How much does the mean of a 30-order sample move? | 90% of 10,000 samples fall between $49.96 and $109.52 |
| What if we grow the sample to 120 orders? | The spread is about half; 90% fall between $61.45 and $91.88 |
| Would 500 more mobile orders be better? | No: samples taken only from mobile cluster about $7 lower, and a larger n does not fix it |
Behind the second row is a distribution: the mean of each of 10,000 different samples of 30 orders. The distribution you will build by simulation looks like this:
samples · Simulation on Bazaar orders.csv (fictional sample data)
In this lesson you will:
Let's make two pairs of words clear first, because we will use them in every lesson after this unit. The set of all the units you care about is the population: all Bazaar orders, all students of a school, all households of a city. The part you can observe is the sample: 30 orders, 10 students, 300 households. Remember from lesson 3: a sample represents the population only if it was chosen at random. Taking whatever is at hand (a convenience sample) gives a biased result.
A number that summarizes the population is a parameter, and a number calculated from a sample is a statistic. The population mean is written μ (Greek "mu") and the population proportion p; the sample mean is written x̄ ("x bar") and the sample proportion p̂ ("p hat"). The parameter is usually unknown: nobody has measured the mean sleep time of all young people in a country. The statistic is what we have. The whole job of statistics is to use the statistic we know to say something honest about the parameter we do not know.
In this lesson we will play a trick: we will treat the 885 orders as the population. Then we know μ, and we can see with our own eyes how close the samples get to it. In real life you do not have this luxury, but learning the method where the population is known lets you trust it where it is not.
To choose at random from the population we use the choice method of the NumPy generator. rng.choice(x, size=30) picks 30 random elements from the array x. In lesson 23, rng.random produced numbers between 0 and 1; choice picks directly from the values you already have. We turn the amount column into a NumPy array with to_numpy() (lesson 14). Let's draw five samples of 30 orders:
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") x = orders["amount"].to_numpy() print("Population:", len(x), "orders | μ = $" + str(round(x.mean(), 2)), "| σ = $" + str(round(x.std(), 2))) rng = np.random.default_rng(42) for i in range(5): sample = rng.choice(x, size=30) print("Sample", i + 1, "mean:", round(sample.mean(), 2))
OutputPopulation: 885 orders | μ = $75.53 | σ = $101.16
Sample 1 mean: 86.78
Sample 2 mean: 84.53
Sample 3 mean: 55.02
Sample 4 mean: 94.07
Sample 5 mean: 78.61The population mean is $75.53, and σ (the standard deviation of the population) is $101.16. On a NumPy array, x.std() divides by n (lesson 14); because we have the whole population, that is the right choice here. The means of the five samples range from $55.02 to $94.07. None of them is 75.53. The $86.78 that customer service found is the first sample: $11.25 above the population. Nobody made a calculation error. Each sample contains a different set of 30 orders, and in 30 orders a few expensive items can easily push the mean up or down. The first misunderstanding falls here: the mean of a sample is not the mean of the population. It is only an estimate of it.
Match the four numbers with the right type:
Is each number a parameter or a statistic?
For each row, pick its match from the list, then check.
Five samples gave five different means. How big can these differences get? Which values are common and which are rare? To see this, we ask the same question many times: draw a sample of 30 orders, take its mean, and repeat this 10,000 times. When statistics from samples of the same size drawn from the same population come out different from each other, this is called sampling variability. It is not a mistake. It is the nature of sampling.
The pattern from lesson 23 works as it is: each row is one trial. rng.choice(x, size=(10_000, 30)) produces a table of 10,000 rows and 30 columns, and each row is a sample of 30 orders. mean(axis=1) takes the mean of each row and gives 10,000 sample means. Then we summarize these 10,000 numbers. For the 5th and 95th percentiles we use np.percentile: the NumPy version of quantile from lesson 15. The only difference is that you write the percent from 0 to 100 (percentile(means, 5) instead of quantile(0.05)).
import pandas as pd import numpy as np x = pd.read_csv("orders.csv")["amount"].to_numpy() rng = np.random.default_rng(42) samples = rng.choice(x, size=(10_000, 30)) means = samples.mean(axis=1) print(samples.shape, means.shape) print("Population mean:", round(x.mean(), 2)) print("Mean of the sample means:", round(means.mean(), 2)) print("Smallest:", round(means.min(), 2), "| largest:", round(means.max(), 2)) lo, hi = np.percentile(means, [5, 95]) print("90% range:", round(lo, 2), "-", round(hi, 2))
Output(10000, 30) (10000,)
Population mean: 75.53
Mean of the sample means: 75.54
Smallest: 32.58 | largest: 194.71
90% range: 49.96 - 109.52Read the lines in order. The first line confirms the shape of the table: 10,000 samples, each with 30 orders, and we have 10,000 means. The second and third lines say something important: the mean of the 10,000 sample means is $75.54, almost the same as the population mean. Single samples miss to the left and to the right, but the misses do not pile up in one direction. This is called the sample mean being unbiased. The fourth line shows the ends: an unlucky sample can give a mean of $32.58, and a very lucky one $194.71. The last line gives the practical answer: 90% of the means of 30-order samples fall between $49.96 and $109.52. The $86.78 from customer service sits comfortably inside this range. It is a completely ordinary sample, but it is $11.25 away from the population mean.
One note: by default choice selects with replacement, so the same order can appear twice in one sample. In a real sample you would not take the same order twice (selection without replacement). As long as the population is 885 orders and the sample is at most 120, the difference between the two ways is small. In this lesson we continue with replacement (the difference is shown in the extra example at the end of the section).
Now run it yourself. The cell draws a histogram of the 10,000 sample means; ax.axvline draws a vertical line at the population mean.
Try it now· not graded; doesn't affect progress
The histogram you just drew is called the sampling distribution: the distribution of the values a statistic (here, the mean) takes across all possible samples of the same size. We cannot count all possible samples, but 10,000 of them are enough to show the shape of the distribution.
This idea is often confused, because there are three separate distributions:
Predict before looking at the numbers:
If we draw the histograms of the three distributions side by side, which one is the narrowest?
Now let's compare the three distributions with numbers:
import pandas as pd import numpy as np x = pd.read_csv("orders.csv")["amount"].to_numpy() rng = np.random.default_rng(42) one = rng.choice(x, size=30) means = rng.choice(x, size=(10_000, 30)).mean(axis=1) for name, d in [("Population (885 amounts)", x), ("One sample (30 amounts)", one), ("Sample means", means)]: print(name, "| std:", round(d.std(), 2), "| min:", round(d.min(), 2), "| max:", round(d.max(), 2))
OutputPopulation (885 amounts) | std: 101.16 | min: 5.81 | max: 899.9
One sample (30 amounts) | std: 100.7 | min: 7.95 | max: 499.8
Sample means | std: 18.47 | min: 32.58 | max: 194.71The standard deviation of the population and of one sample are almost the same ($101.16 and $100.70): the sample is a copy of the population and is just as scattered. The standard deviation of the sample means is $18.47, less than one fifth of that. This number, the standard deviation of the sample means, has its own name and formula; you will see it in lesson 26. In this lesson we will call it simply the spread: "a sample mean typically misses the population mean by about this much."
Draw the three histograms side by side. plt.subplots(1, 3) opens three axes in one row; you use them as axs[0], axs[1], axs[2]. sharex=True puts the horizontal axes of all three on the same scale, so you can compare their widths:
Try it now· not graded; doesn't affect progress
What changes if customer service collects 120 orders instead of 30? Intuition says "it gets better"; let's measure how much better. We run the same simulation for n = 10, 30 and 120. For each n we print three numbers: the spread of the means, the 90% range, and the share of samples that land within $10 of the population mean (the mean of a logical array, as in lesson 7; np.abs takes the absolute value of the difference).
import pandas as pd import numpy as np x = pd.read_csv("orders.csv")["amount"].to_numpy() mu = x.mean() rng = np.random.default_rng(42) for n in [10, 30, 120]: means = rng.choice(x, size=(10_000, n)).mean(axis=1) lo, hi = np.percentile(means, [5, 95]) near = (np.abs(means - mu) <= 10).mean() print("n =", n, "| spread:", round(means.std(), 2), "| 90%:", round(lo, 2), "-", round(hi, 2), "| within $10:", round(near, 2))
Outputn = 10 | spread: 31.85 | 90%: 37.4 - 138.32 | within $10: 0.24
n = 30 | spread: 18.39 | 90%: 50.04 - 109.31 | within $10: 0.41
n = 120 | spread: 9.29 | 90%: 61.45 - 91.88 | within $10: 0.72As n grows, the sampling distribution narrows. For samples of 10 orders, 90% of the means spread from $37.40 to $138.32; samples of 120 orders gather between $61.45 and $91.88. The chance of getting a result within $10 of the population mean goes from 24% to 72%. (The 30 row is not exactly the same as the 18.47 and $49.96–$109.52 in the earlier example: this time the generator drew the samples of 10 first, so the samples of 30 came from later numbers. The difference is the size of chance.)
Now look at the second misunderstanding. Going from 30 to 120 means four times the data, but the spread went from $18.39 to $9.29, only half. Going from 10 to 30 means three times the data, and the spread went from $31.85 to $18.39, about 0.58 times. Doubling the data does not halve the uncertainty; you need four times the data to halve it. The formula that explains why comes in lesson 26. For now, keep in mind what the simulation shows: each extra order gives a little less certainty than the one before.
In the block below, the population is not Bazaar itself but one that looks like it: the code produces 885 right-skewed "order amounts" (rng.exponential gives mostly small numbers and a few very large ones; the name of this distribution does not matter here). Change n and watch how the spread halves with every fourfold increase:
10,000 samples of size n are drawn from a right-skewed population that looks like Bazaar (885 "order amounts"). As n grows, how do the spread of the sample means and the share of samples within $10 of the population mean change?
Pick a value; predict the output first, then look.
1import numpy as np2n = 303rng = np.random.default_rng(42)4population = rng.exponential(75, 885).round(2)5mu = population.mean()6means = rng.choice(population, size=(10_000, n)).mean(axis=1)7print("Population mean:", round(mu, 2))8print("Spread of the means:", round(means.std(), 2))9print("Within $10 share:", round((np.abs(means - mu) <= 10).mean(), 2))
Population mean: 76.7 Spread of the means: 14.33 Within $10 share: 0.51
Faded lines didn't run with this value. From 30 to 120, and from 120 to 480: with each step the data is four times larger, and each time the spread is cut in half (14.33 → 7.18 → 3.58). The share within $10 also rises from 0.51 to 0.99. Certainty does not grow in proportion to the data; to cut the spread in half you need four times the data.
Sampling variability does not happen only with the mean; every statistic moves from sample to sample. Because the next unit starts with proportions, let's see the same idea with the return rate. In the population, 64 of the 885 orders are returns: p = 0.0723. We turn the status column into a True/False array; the return rate of a sample is the mean of that row (lesson 7). If someone sees 50, 100 or 400 orders in a week, how much will the return rate they find move?
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") returned = (orders["status"] == "returned").to_numpy() print("Population return rate p =", round(returned.mean(), 4)) rng = np.random.default_rng(42) for n in [50, 100, 400]: rate = rng.choice(returned, size=(10_000, n)).mean(axis=1) lo, hi = np.percentile(rate, [5, 95]) print("n =", n, "| 90%:", round(lo, 3), "-", round(hi, 3), "| 5% or less:", round((rate <= 0.05).mean(), 2))
OutputPopulation return rate p = 0.0723
n = 50 | 90%: 0.02 - 0.14 | 5% or less: 0.29
n = 100 | 90%: 0.03 - 0.12 | 5% or less: 0.26
n = 400 | 90%: 0.052 - 0.095 | 5% or less: 0.05Although the true rate is 7.2%, in a week of 50 orders the return rate can land anywhere between 2% and 14%: 1 return in 50 orders and 7 returns are both ordinary. The chance of seeing "5% or lower return rate in the sample" is 29% with 50 orders, roughly one week in three. With 400 orders this chance drops to 5%, and the rates gather between 0.052 and 0.095. The pattern from the mean repeats: as n grows, the sampling distribution narrows.
Try it yourself; change n and watch how the histogram of the return rates narrows:
Try it now· not graded; doesn't affect progress
Now connect this table to a decision:
The true return rate is 7.2%. In one week 50 orders arrived and the return rate was 4% (2 returns). Is this result surprising?
So far we have always drawn random samples. In real life the data that is easiest to reach is usually not random: this week's orders, only those from the mobile app, the first 30 records of a list. What do these convenience samples give at Bazaar?
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") month = pd.to_datetime(orders["date"]).dt.month print("May-June:", (month >= 5).sum(), "orders,", round(orders.loc[month >= 5, "amount"].mean(), 2)) print("Mobile only:", (orders["device"] == "mobile").sum(), "orders,", round(orders.loc[orders["device"] == "mobile", "amount"].mean(), 2)) print("First 30 orders:", round(orders["amount"].head(30).mean(), 2))
OutputMay-June: 216 orders, 68.09
Mobile only: 516 orders, 68.83
First 30 orders: 90.77216 and 516 orders are much more data than a random sample of 30. But both are $6.70 to $7.45 below the population mean ($75.53), and the first 30 orders (early January) are more than $15 above. The problem is not the amount but how the sample was chosen: in May–June the baskets got smaller (you saw this in lesson 10), and mobile customers buy cheaper products. These samples represent a slice of the population, not all of it.
To see why a biased selection is not fixed by a large sample, let's compare two ways: choosing at random from all orders every time, and choosing only from mobile orders every time. We repeat both 10,000 times each for n = 30, 120 and 480:
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") x = orders["amount"].to_numpy() mobile = orders.loc[orders["device"] == "mobile", "amount"].to_numpy() mu = x.mean() rng = np.random.default_rng(42) for n in [30, 120, 480]: for name, pool in [("random", x), ("mobile", mobile)]: means = rng.choice(pool, size=(10_000, n)).mean(axis=1) lo, hi = np.percentile(means, [5, 95]) near = (np.abs(means - mu) <= 10).mean() print("n =", n, name, "| center:", round(means.mean(), 2), "| 90%:", round(lo, 2), "-", round(hi, 2), "| within $10:", round(near, 2))
Outputn = 30 random | center: 75.54 | 90%: 49.96 - 109.52 | within $10: 0.41
n = 30 mobile | center: 68.97 | 90%: 46.21 - 100.48 | within $10: 0.36
n = 120 random | center: 75.74 | 90%: 61.55 - 91.99 | within $10: 0.72
n = 120 mobile | center: 68.85 | 90%: 56.24 - 83.47 | within $10: 0.6
n = 480 random | center: 75.62 | 90%: 68.35 - 83.37 | within $10: 0.97
n = 480 mobile | center: 68.88 | 90%: 62.28 - 75.97 | within $10: 0.79Both distributions narrow as n grows, but around different places. The random samples gather around $75.6, and at n = 480, 97% of them are within $10 of the population mean. The mobile samples gather around $68.9; however large n gets, the center does not move, and the within-$10 share gets stuck at 79%. At n = 480, the 90% range of the mobile samples ($62.28–$75.97) only just reaches the population mean at its edge. As n grows, a biased sample moves toward the wrong number with more and more confidence. This is the correction of the "bigger is better" mistake: size helps only in a randomly chosen sample.
Now guide customer service yourself:
Customer service wants to estimate the mean basket. There are two options: this week's 200 mobile orders, or 60 orders chosen at random from all orders of the last six months. Which one do you recommend?
Pick an option and see what happens. There are no points; you can try the other options too.
The same logic works on any topic. Imagine a high school with 1,200 students; the school management wants to know how many hours the students sleep on average per day, but cannot survey 1,200 people. We produce the population with code: rng.normal(7.2, 1.1, 1200) produces 1,200 numbers with a mean of about 7.2 and a standard deviation of about 1.1 hours (you will see the name of this bell-shaped distribution in lesson 26). round(1) rounds the sleep times to 0.1 hours. Then five samples of 10 students, and then 10,000 samples each of 10 and 40 students:
import numpy as np rng = np.random.default_rng(42) sleep = rng.normal(7.2, 1.1, 1200).round(1) print("Population mean:", round(sleep.mean(), 2), "hours") print("Five samples:", rng.choice(sleep, size=(5, 10)).mean(axis=1).round(2)) for n in [10, 40]: means = rng.choice(sleep, size=(10_000, n)).mean(axis=1) print("n =", n, "| spread:", round(means.std(), 2), "hours")
OutputPopulation mean: 7.17 hours
Five samples: [7.2 6.47 6.81 7.17 7.7 ]
n = 10 | spread: 0.34 hours
n = 40 | spread: 0.17 hoursThe population mean is 7.17 hours. Five samples of 10 students give results between 6.47 and 7.70 hours: asking 10 people from one class and saying "students at our school sleep 6.5 hours on average" opens the door to a one-hour mistake. The spread is 0.34 hours with 10 students and 0.17 hours with 40: four times the students, half the spread. This is the Bazaar pattern once more.
Put the lines of this simulation in the right order:
Put the lines of the simulation that finds the spread of the means of 40-student samples in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
You may have noticed something since the start of this unit: although the population (order amount) is strongly right-skewed, the histogram of the sample means had its peak in the middle and fell away on both sides like a bell. This is not a coincidence; you will see the name of this shape and the formula for "how much does a mean move" in the next lesson.
The sample of customer service is the first sample drawn in section 1. Let's compare its mean, its median, and the expensive orders in it with the population.
import pandas as pd import numpy as np x = pd.read_csv("orders.csv")["amount"].to_numpy() rng = np.random.default_rng(42) sample = rng.choice(x, size=30) print("Sample mean:", round(sample.mean(), 2), "| median:", np.median(sample)) print("Population mean:", round(x.mean(), 2), "| median:", np.median(x)) print("Orders over $250 in the sample:", (sample > 250).sum())
OutputSample mean: 86.78 | median: 52.205
Population mean: 75.53 | median: 44.95
Orders over $250 in the sample: 2There are two orders over $250 among the 30; these two are enough to move the mean $11.25 above the population mean. The median is also higher than the population median. A single sample depends on which orders happened to fall into it; you cannot see this from the sample alone.
choice selects with replacement by default. replace=False stops the same order from appearing twice in one sample. Let's compare the spread of the two ways with samples of 30 orders; because selection without replacement has to be done one sample at a time, we use a loop.
Reporting the statistic of a single sample as an exact number:
Output"Mean basket is $86.78; we are planning the campaign budget on it."This sentence comes from a single sample of 30 orders, but everyone who reads it thinks it is the mean of all orders. In the simulation, the means of 30-order samples moved between $49.96 and $109.52; with the same method, another week could easily have given $55. The right way is to write next to the number the size of the sample, how it was chosen, and how much it can move: "In 30 random orders the mean is $86.78; the means of samples this size can move between about $50 and $110."
rng.choice(x, size=(10_000, n)).mean(axis=1)); it is not mixed up with the distribution of the data, and it is much narrower. In a random sample its center is at the population mean (unbiased).Next lesson: The bell shape in the histogram of the sample means is called the normal model; you will calculate how much a mean moves with a single formula, without a simulation.
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.
| — | number of samples |
|---|---|
| 25-37.5 | 11 |
| 37.5-50 | 495 |
| 50-62.5 | 2035 |
| 62.5-75 | 2868 |
| 75-87.5 | 2283 |
| 87.5-100 | 1298 |
| 100-112.5 | 610 |
| 112.5-125 | 261 |
| 125-137.5 | 93 |
| 137.5-150 | 31 |
| 150+ | 15 |
import pandas as pd import numpy as np x = pd.read_csv("orders.csv")["amount"].to_numpy() rng = np.random.default_rng(42) wr = [rng.choice(x, size=30).mean() for i in range(10_000)] wo = [rng.choice(x, size=30, replace=False).mean() for i in range(10_000)] print("With replacement spread:", round(np.std(wr), 2)) print("Without replacement spread:", round(np.std(wo), 2))
OutputWith replacement spread: 18.47
Without replacement spread: 18.19The difference is $0.28: negligible for a sample of 30 from a population of 885 orders. As the sample gets close to a large part of the population, the spread without replacement also gets smaller; this is why we keep n at 120 at most in this lesson.