From Samples to Certainty

How to make an honest statement about everyone from a sample of a few: sampling, the central limit theorem, standard errors, confidence intervals, sample sizes and the bootstrap.

true mean price $3,933 $2,000 $3,000 $4,000 $5,000 $6,000 20 random samples of 50 diamonds, one 95% interval each (1 miss, in pink) true mean price $3,933 $2,000 $3,000 $4,000 $5,000 $6,000 20 samples of 50, one 95% interval each (1 miss)
Real data: the 53,940 diamonds in seaborn's diamonds dataset, treated as a population. Each line is a 95% confidence interval built from a different random sample of 50. The true mean never moves; the intervals do, and about 1 in 20 misses.

Everything so far has described data you already have, or assumed you knew the true parameters, like Day 10's μ and σ. Real work rarely gives you either. You have a sample, and you want to say something honest about the much bigger group it came from. That's inferential statistics, and Part III is about it.

Why does any of this matter?

Say you're a data scientist at Netflix. There are hundreds of millions of subscribers around the world, and your product team walks up and asks: what's the average number of minutes our users watch per day?

Netflix keeps a record every time anyone hits play, pause or stop, for every user. So here's a fair question: why bother sampling when the full data is right there? If all anyone cared about was the past, this wouldn't even be a debate. Every subscriber's complete history is already sitting in a database. Add it all up, divide by the number of people, and that's the actual average. Not an estimate, not a guess: the real number. When you have everyone's data like that, it's called a census, and a census has no sampling error at all. If the question really is "what happened last week?" and the full data is affordable to query, you should simply compute it.

So why do companies still sample? There are three real reasons.

First, most decisions aren't really about the past at all; they're about what happens next. Will people watch more if Netflix shifts towards longer movies instead of short episodes? What will next quarter look like? What will someone who hasn't even signed up yet probably do? None of that is sitting in any log file, because it hasn't happened yet. The best you can do is treat your most recent data as a sample from an ongoing process, and use it as a stand-in for a future that doesn't exist yet.

Second, some questions can't be answered from existing data no matter how complete it is. If a company wants to know how users would react to an offer nobody has ever seen, no log anywhere holds the answer. The only way to find out is to show the offer to some people and watch what happens. Those people are a sample, by necessity.

Third, it's practical. Running a query against tens of billions of raw events takes time and costs money. Doing that over and over, every time someone wants to check an idea, gets expensive fast. Surveys, lab tests, manual fraud reviews and factory inspections are worse: every unit you measure costs real money. So people pull a sample, get a fast answer, and run the full calculation only when the exact number actually matters.

Here's what actually happens in practice: you take a sample, measure it, crunch the numbers, and make a confident statement about everyone, along with an honest range for how wrong you might be. That's the whole idea behind inferential statistics: working out a value you can't see directly from a smaller piece you can.

And that's roughly the line between two kinds of work. Describing what already happened is reporting. Using data to say what is likely to be true more widely, or to happen next, and what to do about it, is where data science starts.

Five problems to solve

Before any theory, here are five situations of the kind data teams at large companies face, each solved by the end of this article with the tools it introduces. The company names make the setting concrete, but the scenarios are illustrations: the sample sizes, averages and data are invented or simulated for teaching, not any company's real figures or methods.

Notice how the five differ. In four of them, the company already logs everything that has happened; the sampling is there because the question is about the future, about a process that is still running, or because querying everything every time is too slow. In the fourth one, Spotify's offer, no log anywhere could answer the question, however good the data collection is.

Problem 1: How long do Netflix subscribers actually watch?

Netflix wants the true average daily watch time across all its subscribers, to help decide how much to invest in longer movies versus short episodes. That decision is about future spending, and future viewing behaviour obviously has no logs yet. So instead of crunching the full historical dataset every time someone wants to check this, the team takes a random sample of 1,000 subscribers, looks at their daily watch time, and uses it to estimate the average for everyone, along with how sure it can be. Keep that number in mind: 1,000 people turns out to be plenty, once we build the confidence interval later in this article.

The question: "Our sample averaged 108 minutes (1.8 hours) a day, with a standard deviation of 45 minutes. What's the real average across all subscribers, and how sure are we?"

Problem 2: What's the real average Uber trip time in Mumbai?

Uber runs a huge number of trips every day in Mumbai. To set driver incentives and pricing for next month, a month that hasn't happened yet, the team needs a good estimate of what trip times will look like. So it takes a sample of 2,000 recent trips, the most representative slice available right now, and builds a confidence interval around the average. That interval becomes the best guess for what's coming, as long as conditions next month resemble the recent past.

The question: "Our sample shows an average trip of 22 minutes, with a standard deviation of 12 minutes. What range can we confidently say contains the real average for all Mumbai trips?"

Problem 3: Is Swiggy's delivery really under 30 minutes?

Suppose Swiggy advertises "delivery in 30 minutes or less". The operations team wants to check, right now, whether that's actually true, one city at a time. Deliveries keep happening every minute, so there's no such thing as a finished population to check: it's always still arriving. Starting with Bangalore, the team takes the 500 most recent orders and uses them to estimate how the city is doing right now. Delivery times are skewed: most orders arrive in under half an hour, but a minority run very late because of traffic, rain or a busy kitchen.

The question: "Is our delivery promise actually being kept in Bangalore, and how confident can we be?" As we'll see, the hardest part of this problem isn't the maths. It's choosing the statistic that matches the promise.

Problem 4: How many Spotify free users would go Premium?

Spotify's growth team wants to know what percentage of its free users would upgrade to Premium if they saw a special discount offer. Here's the catch: there's genuinely no way to answer this from data already on hand, because nobody has ever seen this exact offer before. There's no record anywhere of how the full base of free users would react to something they've never been shown. The only way to find out is to show it to some people and watch what happens. So the team shows the offer to 10,000 randomly chosen free users and tracks how many upgrade.

The question: "1,200 of the 10,000 upgraded, which is 12%. What's the real upgrade rate across all free users, and how much uncertainty is there?"

Problem 5: How big is an unusually large Stripe transaction?

Stripe processes payments for a vast number of small businesses. Its risk team wants to set a threshold above which a transaction from a business with fewer than 10 employees counts as unusually large and gets extra fraud review. A sensible threshold is the 90th percentile of transaction sizes: the value that only 1 in 10 transactions exceeds. A fraud threshold is naturally about the future, since its whole job is to catch large transactions before they clear, so it has to be built from recent data as a stand-in for what's coming. The team samples 4,000 recent transactions from businesses that fit the criteria. Transaction sizes are heavily skewed: most are small, and a few are very large.

The question: "What's our best estimate of the 90th percentile of transaction sizes, and how much could it be off because we only looked at 4,000 transactions?"

Notice the pattern across all five. The population is something that hasn't happened yet, something still happening, or something too expensive to check in full every time. A manageable sample can be measured right now, and the population value has to be worked out from it, honestly, with the uncertainty stated up front. Let's build the toolkit to solve them.

Part 1: Sampling

Population and sample

The population is the whole group your question is about. The sample is the part of it you actually measure. A cook tasting soup doesn't drink the whole pot: a well-stirred spoonful tells them about the pot. The spoonful is the sample, the pot is the population, and the stirring matters as much as the spoon.

Population: everyone μ, σ (unknown) Sample: the ones you measure x̄, s (calculated) draw at random infer back Population: everyone μ, σ (unknown) Sample: the ones you measure x̄, s (calculated) draw at random infer back
You never see μ and σ directly. You calculate x and s from a sample, and inference is the careful process of working back from one to the other.
TermSymbolMeaning
Population meanμ (mu)The true average across the whole population
Population standard deviationσ (sigma)The true spread across the whole population
Sample meanx (x-bar)The average of your sample
Sample standard deviationsThe spread of your sample (with n − 1, Day 4)
Sample proportionp̂ (p-hat)The share of your sample with some property
Sample sizenHow many observations are in the sample

A handy rule from Day 1: Greek letters belong to the population and are almost never known; Latin letters belong to the sample and are what you calculate. Inference means using x and s to say something about μ and σ.

Ways to sample

Simple random every unit equally likely Stratified random within each group Systematic every k-th unit Simple random every unit equally likely Stratified random within each group Systematic every k-th unit
Three ways to pick 12 units out of 96. Stratified sampling guarantees each group (shaded) gets its share; systematic sampling takes every 8th unit.

The one rule that matters more than any formula in this article: a sample must represent the population. Statistics can measure the random error in a fair sample. They can't fix a biased one.

Real case: "Dewey Defeats Truman", 1948

Before the 1948 US presidential election, the major pollsters, Gallup, Roper and Crossley, all predicted that Thomas Dewey would beat Harry Truman. The Chicago Daily Tribune printed about 150,000 copies with the headline "DEWEY DEFEATS TRUMAN". Truman won by more than two million votes.

Two sampling mistakes were blamed. The polls used quota sampling: interviewers had to fill quotas for each demographic group, but chose for themselves whom to interview, which let their own preferences creep in. And the pollsters stopped polling weeks before the election, missing late changes of mind. The lasting change that followed was the industry's move to probability sampling, where chance, not the interviewer, decides who is asked. (Day 1's Literary Digest poll of 1936 is the other classic warning: a huge sample can't fix a biased one.)

Sampling error is normal

Even a perfectly fair sample won't hit the true value exactly. The gap between the sample mean and the population mean is the sampling error, x − μ. It isn't a mistake: draw 100 different random samples and you'll get 100 slightly different means. Inferential statistics exists to measure how big that random variation is likely to be.

Part 2: The central limit theorem

Day 10 introduced the central limit theorem (CLT). Here it is in the form we need. If you take many random samples of size n from a population with mean μ and standard deviation σ and calculate each sample's mean:

Standard error (SE) = σ√n     estimated in practice by s√n

Let's check it on real data. The diamonds dataset in seaborn lists 53,940 diamonds with their prices. Prices are heavily skewed: most diamonds are cheap and a few are very expensive. Treat all 53,940 as the population, so we know the true mean, and draw thousands of samples of 50:

Pythonimport numpy as np import seaborn as sns from scipy import stats price = sns.load_dataset("diamonds")["price"].to_numpy() mu, sigma = price.mean(), price.std() print(f"Population: {len(price):,} diamonds, mean ${mu:,.0f}, SD ${sigma:,.0f}, skewness {stats.skew(price):.2f}") rng = np.random.default_rng(1) means = np.array([rng.choice(price, size=50, replace=False).mean() for _ in range(10_000)]) print(f"Average of the sample means: ${means.mean():,.0f}") print(f"SD of the sample means: ${means.std():,.0f} (theory: sigma / sqrt(50) = ${sigma / np.sqrt(50):,.0f})") print(f"Skewness of the sample means: {stats.skew(means):.2f}")
OutputPopulation: 53,940 diamonds, mean $3,933, SD $3,989, skewness 1.62 Average of the sample means: $3,937 SD of the sample means: $563 (theory: sigma / sqrt(50) = $564) Skewness of the sample means: 0.24
$0k $5k $10k $15k 53,940 diamond prices the population: heavily skewed $2k $3k $4k $5k $6k 10,000 averages of 50 prices close to a bell around the true mean $0k $5k $10k $15k 53,940 diamond prices the population: heavily skewed $2k $3k $4k $5k $6k 10,000 averages of 50 prices close to a bell around the true mean
Real diamond prices are badly skewed. Averages of 50 randomly chosen prices form a near-symmetric bell around the true mean (dashed line), with a spread that matches σ/√n.

The sample means centre on the true mean, their spread matches σ/√n almost exactly, and the skewness has dropped from 1.62 to about 0.24. That bell shape is what lets us use the normal distribution, and its 1.96, to build intervals around a sample mean even when the data itself isn't normal.

Standard error: how precise is an average?

The standard deviation describes how spread out individual values are. The standard error describes how much a sample mean would vary from sample to sample: how precise your estimate is. Collecting more data doesn't make diamonds more alike, so s doesn't shrink as n grows. But the average of more diamonds is a steadier number, so the SE does.

n = 10: SE 14.2 n = 100: SE 4.5 n = 400: SE 2.2 n = 1,000: SE 1.4 0 5 10 15 0 250 500 750 1,000 sample size n standard error (minutes), with s = 45 n = 10: SE 14.2 n = 100: SE 4.5 n = 1,000: SE 1.4 0 5 10 15 0 250 500 750 1,000 sample size n standard error (minutes), with s = 45
Standard error for s = 45 minutes. It falls fast at first, then flattens: quadrupling the sample from 100 to 400 only halves the SE.

Because of the square root, precision gets expensive. To halve the standard error you need four times the data; to cut it to a third, nine times. Going from 100 to 1,000 observations makes your estimate about 3.2 times more precise, not 10 times.

Sampling a big share of the population

The SE formula assumes the population is much bigger than the sample, which is almost always true. If you sample a large share of a finite population, multiply the SE by √((N − n)/(N − 1)), the finite population correction. Sample 1,000 from a million and it's 0.9995, which changes nothing. Measure everyone (n = N) and it's 0: a census has no sampling error at all. Its remaining errors come from measurement and definitions, not from chance.

Part 3: Confidence intervals

One number isn't enough

If a sample of subscribers averages 108 minutes a day, telling the product team "the average is exactly 108 minutes" oversells it. That's a point estimate, and it's almost certainly a little off. A better answer is "we're 95% confident the true average is between 105.2 and 110.8 minutes". That's a confidence interval: a range built from the sample, with a stated level of confidence.

CI = x ± t* × s√n
x is the centre. t* is the critical value for your confidence level (close to 1.96 for 95% with large samples). s/√n is the standard error. t* × SE is the margin of error.

What "95% confident" really means

This is the most misunderstood idea in statistics. The true mean is a fixed number; it doesn't move. What moves is the interval, because every new sample gives a different one. "95% confidence" describes the method: if you repeated the sampling over and over, about 95% of the intervals built this way would contain the true mean. Any one interval either contains it or doesn't. You just don't know which, which is why you report the range.

Think of fishing with a net designed to catch the fish 95% of the time. Each cast either catches it or misses, and the net's design is what gives you confidence. The hero image at the top of this page shows 20 such casts on real diamond prices: 19 catch the true mean and 1 misses.

We can check the "95%" claim directly, since for the diamonds we know the true mean:

Pythondef coverage(n, repeats=2000, seed=5): rng = np.random.default_rng(seed) hits = 0 for _ in range(repeats): s = rng.choice(price, size=n, replace=False) low, high = stats.t.interval(0.95, df=n - 1, loc=s.mean(), scale=stats.sem(s)) hits += low <= mu <= high return hits / repeats for n in [10, 50, 200]: print(f"n = {n:3}: {coverage(n):.1%} of 95% intervals contain the true mean")
Outputn = 10: 89.0% of 95% intervals contain the true mean n = 50: 94.2% of 95% intervals contain the true mean n = 200: 94.0% of 95% intervals contain the true mean

With samples of 50 or 200, the intervals catch the true mean about 94% of the time, close to the promised 95%. With samples of 10 from this badly skewed population, only about 89% do, because the CLT hasn't fully kicked in yet. The formula's promise holds approximately, and the approximation needs a big enough sample when the data is skewed.

Critical values: how wide to cast the net

Confidence levelz* (large samples)In words
90%1.645A narrower net, less sure
95%1.960The usual choice
99%2.576A wider net, more sure

More confidence always means a wider interval. You can't get more certainty without giving up some precision, unless you collect more data.

z or t?

The z-values above assume you know the population's standard deviation σ. You almost never do; you estimate it with s, which adds extra uncertainty, especially in small samples. The t-distribution accounts for that. It looks like the normal curve with fatter tails, and its critical values depend on the degrees of freedom, n − 1.

1.96 2.78 -4 -2 0 2 4 normal (z) t with 4 degrees of freedom (n = 5) 1.96 2.78 -4 -2 0 2 4 normal (z) t with 4 degrees of freedom (n = 5)
With a sample of 5, the t-distribution's tails are much fatter than the normal's, so a 95% interval needs 2.78 standard errors instead of 1.96.

The practical rule is simple: when you estimate σ with s, use t. For small samples it gives noticeably wider, more honest intervals. For large samples it's almost identical to z, so you lose nothing.

Pythonfor n in [5, 15, 30, 100, 1000]: print(f"n = {n:4}: t* = {stats.t.ppf(0.975, df=n - 1):.3f}") print(f"z* (normal): {stats.norm.ppf(0.975):.3f}")
Outputn = 5: t* = 2.776 n = 15: t* = 2.145 n = 30: t* = 2.045 n = 100: t* = 1.984 n = 1000: t* = 1.962 z* (normal): 1.960
Real case: a brewer invents the t-distribution

William Sealy Gosset worked as a chemist at the Guinness brewery in Dublin, where experiments on barley and hops often involved tiny samples, sometimes just a handful of measurements. The normal-based methods of his day gave intervals that were too narrow for samples that small. Gosset worked out the correct distribution and published it in 1908 in the journal Biometrika under the pen name "Student", because Guinness preferred its staff not to publish under their own names. That's why it's still called Student's t-distribution.

Two different questions are easy to mix up. "Is n big enough for the CLT?" is about the shape of the sampling distribution, and depends on how skewed the data is. "z or t?" is about whether you know σ. The common "use z once n is 30 or more" shortcut blends the two; using t whenever you estimate σ avoids the confusion.

Confidence intervals for proportions

For a yes/no outcome, such as converted or not, the sample proportion p̂ replaces the mean. By the CLT, p̂ is approximately normal with standard error √(p̂(1 − p̂)/n):

CI = p̂ ± z* × √p̂(1 − p̂)n
This simple version works when there are at least about 10 successes and 10 failures in the sample. For small samples or proportions near 0 or 1, use a better method such as the Wilson interval, which SciPy provides.

Part 4: How big should the sample be?

Ideally you answer this before collecting any data. Too small and your interval is too wide to act on ("the conversion rate is somewhere between 3% and 45%"). Too big and you've spent time and money on precision nobody needed.

Flip the margin-of-error formula around. If you need a margin of error no bigger than E:

For a mean: n = (z* × σ)2E2    For a proportion: n = (z*)2 × p(1 − p)E2
σ and p are your best guesses, from a pilot study or past data. With no idea about p, use 0.5: it makes p(1 − p) as large as possible, giving the safest, largest sample size.

E, the margin of error you can live with, is a business decision, not a statistical one. "Within ±5 minutes" and "within ±1 minute" lead to very different budgets.

Pythondef n_for_mean(margin, sd, confidence=0.95): z = stats.norm.ppf(1 - (1 - confidence) / 2) return int(np.ceil((z * sd / margin) ** 2)) def n_for_proportion(margin, p=0.5, confidence=0.95): z = stats.norm.ppf(1 - (1 - confidence) / 2) return int(np.ceil(z ** 2 * p * (1 - p) / margin ** 2)) print(f"Watch time, +/-3 min, SD 45: n = {n_for_mean(3, 45):,}") print(f"Watch time, +/-1 min, SD 45: n = {n_for_mean(1, 45):,}") print(f"Watch time, +/-3 min, 99% confident: n = {n_for_mean(3, 45, 0.99):,}") print(f"Conversion, +/-1 point, guess 12%: n = {n_for_proportion(0.01, 0.12):,}") print(f"Conversion, +/-1 point, no guess: n = {n_for_proportion(0.01):,}")
OutputWatch time, +/-3 min, SD 45: n = 865 Watch time, +/-1 min, SD 45: n = 7,779 Watch time, +/-3 min, 99% confident: n = 1,493 Conversion, +/-1 point, guess 12%: n = 4,057 Conversion, +/-1 point, no guess: n = 9,604

Three lessons. Precision is expensive: tightening the margin from ±3 to ±1 minute needs 9 times the data. Certainty costs too: going from 95% to 99% confidence needs about 73% more. And a decent guess helps: knowing the conversion rate is around 12% cuts the required sample from 9,604 to 4,057.

Two practical notes. If you don't know σ, a small pilot study of 30 to 50 observations gives you an s to plug in. And if the formula asks for more data than you can afford, run it the other way: plug in the n you can afford and see what margin of error you'd get, then decide together whether that's good enough for the decision at hand.

Part 5: The bootstrap

When there's no formula

The interval formulas so far work for means and proportions. But what about the median delivery time? The 90th percentile of transaction sizes? A ratio, or a model's accuracy? For many statistics there's no simple standard-error formula. That's where the bootstrap comes in.

Real case: Efron's bootstrap, 1979

The statistician Bradley Efron introduced the bootstrap in 1979, in a paper in The Annals of Statistics titled "Bootstrap methods: another look at the jackknife". The name comes from the phrase "pulling yourself up by your own bootstraps": the method uses the sample to estimate its own uncertainty. It only became practical once computers made it cheap to repeat a calculation thousands of times.

How it works

You can't draw new samples from the population. But if your sample is a fair miniature of the population, you can draw new samples from it:

  1. Draw n values from your sample with replacement, so some values appear twice or more and others not at all. This is a bootstrap resample.
  2. Calculate the statistic you care about (median, percentile, anything) on that resample.
  3. Repeat thousands of times.
  4. The middle 95% of the results, from the 2.5th to the 97.5th percentile, is a 95% bootstrap confidence interval.

Sampling with replacement is essential. Without it, every resample would be the same values shuffled, giving the same median every time and no information about uncertainty. On average, each resample contains about 63% of the original values (the rest are repeats), which is where the variety comes from.

Here it is on real data: a 95% interval for the median of the 244 restaurant bills in the tips dataset.

Pythonbills = sns.load_dataset("tips")["total_bill"].to_numpy() print(f"Sample median: ${np.median(bills):.2f}") rng = np.random.default_rng(42) boot_medians = np.array([np.median(rng.choice(bills, size=len(bills), replace=True)) for _ in range(10_000)]) low, high = np.percentile(boot_medians, [2.5, 97.5]) print(f"95% bootstrap CI for the median: ${low:.2f} to ${high:.2f}") # SciPy has this built in result = stats.bootstrap((bills,), np.median, confidence_level=0.95, method="percentile", random_state=42) ci = result.confidence_interval print(f"scipy.stats.bootstrap: ${ci.low:.2f} to ${ci.high:.2f}")
OutputSample median: $17.80 95% bootstrap CI for the median: $16.49 to $18.67 scipy.stats.bootstrap: $16.53 to $18.66
2.5th pct $16.49 97.5th pct $18.67 $16 $17 $18 $19 $20 median bill in each of 10,000 bootstrap resamples middle 95%: $16.49 to $18.67 $16 $17 $18 $19 $20 median bill in each of 10,000 bootstrap resamples
10,000 bootstrap medians of the restaurant bills. Their middle 95% is the confidence interval. The jagged shape is normal for a median: with 244 bills, the median can only take a limited set of values.

What the bootstrap does and doesn't do

Formula-based CI (t, z)Bootstrap CI
Works forMeans and proportions, cleanlyAlmost any statistic: medians, percentiles, ratios, model metrics
Main assumptionRandom sample; n large enough for the CLTRandom sample that represents the population well
Small samplesUse t; still fragile with skewed dataAlso fragile: intervals tend to be too narrow
ComputationOne formulaThousands of repeats (fast on a computer)
The bootstrap isn't magic

It can't fix a biased sample, since it only ever reuses the data you have. With small samples its intervals tend to be too narrow. It struggles with extreme percentiles, where the sample has few values to resample. And plain resampling breaks the structure of data that isn't independent, such as time series, where a variant called the block bootstrap is used instead. Within those limits it's one of the most useful tools a data scientist has.

Part 6: Solving the five problems

Time to go back to the five problems from the start and solve every one of them with real Python code. Remember that the data in each is invented or simulated for teaching.

Solution 1: Netflix's average watch time

Problem: a random sample of 1,000 subscribers shows an average daily watch time of 108 minutes (1.8 hours), with a standard deviation of 45 minutes. Build a 95% confidence interval for the real average across all subscribers.

This is a mean, the sample is large, and we only know the sample's standard deviation s, not σ. So we use the t-based interval: x ± t* × s/√n.

Pythonn, x_bar, s = 1000, 108, 45 se = s / np.sqrt(n) # standard error t_star = stats.t.ppf(0.975, df=n - 1) # critical value for 95% moe = t_star * se # margin of error low, high = x_bar - moe, x_bar + moe print(f"Standard error: {se:.2f} minutes") print(f"Critical value: t* = {t_star:.3f}") print(f"Margin of error: {moe:.2f} minutes") print(f"95% CI: {low:.1f} to {high:.1f} minutes ({low / 60:.2f} to {high / 60:.2f} hours)")
OutputStandard error: 1.42 minutes Critical value: t* = 1.962 Margin of error: 2.79 minutes 95% CI: 105.2 to 110.8 minutes (1.75 to 1.85 hours)

Netflix can say, with 95% confidence, that the real average daily watch time across all subscribers is between about 105 and 111 minutes, or 1.75 to 1.85 hours. Both ends sit comfortably under 2 hours, useful context for a team deciding where to put content money. Notice that with n = 1,000, t* (1.962) is practically the same as z* (1.960), exactly as the "z or t?" section promised.

Hold on: why not just look at every subscriber?

It's a fair question. The full viewing history of every subscriber is already sitting in a database. If the goal is simply the most precise possible number for last week's average, querying everyone wins: it's a census, and a census has no sampling error at all. (The finite population correction from Part 2 is exactly 0 when n equals N.) There's no statistical reason to prefer a sample when the whole population is right there and affordable to check.

But look at what the sample already gives you: the average to within about ±2.8 minutes. Nobody decides whether to commission more two-hour films or more 22-minute episodes based on knowing the average to the nearest second. Once a sample is precise enough to answer the real question, extra precision buys nothing the decision can use.

There's a practical reason too. A decision like this rarely comes from one query. A team digging into it slices the data by genre, region, device and how long people have subscribed, testing many angles before making a recommendation. Each slice runs in seconds on a sample. The same exploration against the full event log, billions of play, pause and stop events rather than one tidy row per subscriber, is slower and costlier to repeat a dozen times. A common pattern is to explore on samples and confirm the final number on the full data once, just before it goes into a decision.

And here's the point really worth sitting with. Even a perfect, zero-error average across every subscriber only shows what happened under the content mix Netflix already has. It can't say what would happen if Netflix shifted investment towards longer content, because nobody has made that change yet. That's a question about cause and effect, and no historical average, however exact, answers it on its own. Finding out "will people watch more if we change the mix?" is what experiments and hypothesis tests are for, which is where Day 12 and Day 13 pick up.

Solution 2: Uber's average trip time in Mumbai

Problem: a sample of 2,000 recent Mumbai trips has an average of 22 minutes and a standard deviation of 12 minutes. Build a 99% confidence interval for the real average trip time.

Same recipe as Solution 1, but with 99% confidence the critical value is bigger, so the net is wider. SciPy's stats.t.interval does the whole calculation in one line:

Pythonn, x_bar, s = 2000, 22, 12 se = s / np.sqrt(n) low, high = stats.t.interval(0.99, df=n - 1, loc=x_bar, scale=se) print(f"Standard error: {se:.3f} minutes") print(f"Critical value: t* = {stats.t.ppf(0.995, df=n - 1):.3f}") print(f"99% CI: {low:.2f} to {high:.2f} minutes")
OutputStandard error: 0.268 minutes Critical value: t* = 2.578 99% CI: 21.31 to 22.69 minutes

Uber can be 99% confident the real average trip time in Mumbai is between about 21.3 and 22.7 minutes. Even at 99% confidence the interval is tight, mostly because 2,000 trips is a large sample: the standard error is only about a quarter of a minute. That's precise enough to set driver incentives and pricing with real confidence.

One caveat the interval can't capture: recent trips only stand in for next month if conditions stay similar. A festival season, the monsoon or a new metro line can shift trip times in ways no confidence interval can see. The interval measures random sampling error, not the risk that the future differs from the past.

Solution 3: Swiggy's delivery promise

Problem: Swiggy has 500 recent Bangalore orders. Most arrive in about 28 minutes, but a minority run very late. Is the "30 minutes or less" promise being kept?

Delivery times are skewed, so the median describes a typical order better than the mean. There's no simple formula for the median's standard error, so we bootstrap it. The data below is simulated: 450 ordinary orders around 28 minutes plus 50 slow ones around 65 minutes.

Pythonrng = np.random.default_rng(7) times = np.concatenate([rng.normal(28, 5, 450), # most orders: around 28 minutes rng.normal(65, 10, 50)]) # a slow minority: around 65 minutes times = np.clip(times, 10, 120) res = stats.bootstrap((times,), np.median, confidence_level=0.95, method="percentile", random_state=42) print(f"Sample mean: {times.mean():.1f} minutes") print(f"Sample median: {np.median(times):.1f} minutes (mean above median: right-skewed)") print(f"95% bootstrap CI for the median: {res.confidence_interval.low:.1f} to {res.confidence_interval.high:.1f} minutes")
OutputSample mean: 30.9 minutes Sample median: 28.0 minutes (mean above median: right-skewed) 95% bootstrap CI for the median: 27.7 to 28.4 minutes

The median is about 28 minutes, and its whole confidence interval sits below 30. The mean is higher, pulled up by the late orders, exactly as Day 3 would predict for skewed data. It's tempting to stop here and declare the promise kept. That would be a mistake.

Read the promise again: "delivery in 30 minutes or less". It's a promise about each order, not about the typical order. A median under 30 only tells you that half the orders arrive in time. The customer whose food takes 65 minutes doesn't care that the median was 28. The statistic that actually matches the promise is the share of orders that take longer than 30 minutes, and that's a proportion, so it has its own confidence interval:

Pythonlate = int((times > 30).sum()) ci = stats.binomtest(late, len(times)).proportion_ci(confidence_level=0.95, method="wilson") print(f"Orders over 30 minutes: {late} of {len(times)} = {late / len(times):.1%}") print(f"95% CI for the share of late orders: {ci.low:.1%} to {ci.high:.1%}")
OutputOrders over 30 minutes: 174 of 500 = 34.8% 95% CI for the share of late orders: 30.8% to 39.1%

Somewhere between about 31% and 39% of orders, roughly one in three, break the promise. The median made the service look fine; the late share shows a real problem worth fixing. The lesson goes far beyond deliveries: choose the statistic that matches the question before you choose the method. A perfectly computed interval for the wrong statistic still gives the wrong answer.

Solution 4: How many Spotify free users would go Premium

Problem: Spotify shows a discount offer to 10,000 randomly chosen free users, and 1,200 of them upgrade to Premium: 12%. What's the 95% confidence interval for the real upgrade rate across all free users?

This is a proportion, so we use the proportion version of the interval: p̂ = x/n, SE = √(p̂(1 − p̂)/n), and CI = p̂ ± z* × SE. The simple formula needs at least about 10 successes and 10 failures, and with 1,200 upgrades and 8,800 non-upgrades that's easily met. We'll also compute the Wilson interval to check:

Pythonx, n = 1200, 10_000 p_hat = x / n se = np.sqrt(p_hat * (1 - p_hat) / n) z_star = stats.norm.ppf(0.975) print(f"Sample proportion: {p_hat:.1%}") print(f"Standard error: {se:.4f}") print(f"95% CI (simple formula): {p_hat - z_star * se:.2%} to {p_hat + z_star * se:.2%}") wilson = stats.binomtest(x, n).proportion_ci(confidence_level=0.95, method="wilson") print(f"95% CI (Wilson): {wilson.low:.2%} to {wilson.high:.2%}")
OutputSample proportion: 12.0% Standard error: 0.0032 95% CI (simple formula): 11.36% to 12.64% 95% CI (Wilson): 11.38% to 12.65%

Both methods agree: Spotify can be 95% confident the real upgrade rate is between about 11.4% and 12.6%. That range is narrow enough to build a revenue forecast around. To turn it into a number of new subscribers, multiply both ends by the number of free users who would see the offer, and report the result as a range too, never as a single figure.

One condition matters more than the arithmetic. The result applies to the kind of users the 10,000 were drawn from. If they were chosen at random from all free users worldwide, it describes all free users. If they all came from one country, or from users who had just opened the app, the 12% describes that group, and could be quite different elsewhere.

Solution 5: Stripe's 90th percentile transaction size

Problem: Stripe samples 4,000 recent transactions from small businesses. The risk team needs the 90th percentile of transaction sizes, with a 95% confidence interval, to set a fraud-review threshold.

Money data like this is usually heavily skewed, so we simulate it with a log-normal distribution, a common model for amounts. There's no simple formula for the standard error of a percentile, which makes this a job for the bootstrap:

Pythonrng = np.random.default_rng(21) amounts = rng.lognormal(mean=5.5, sigma=1.2, size=4000) # skewed, like most money data print(f"Sample mean: ${amounts.mean():,.0f}") print(f"Sample median: ${np.median(amounts):,.0f}") print(f"Sample 90th percentile: ${np.percentile(amounts, 90):,.0f}") res = stats.bootstrap((amounts,), lambda a: np.percentile(a, 90), confidence_level=0.95, method="percentile", random_state=42) print(f"95% bootstrap CI for the 90th percentile: ${res.confidence_interval.low:,.0f} to ${res.confidence_interval.high:,.0f}")
OutputSample mean: $500 Sample median: $249 Sample 90th percentile: $1,128 95% bootstrap CI for the 90th percentile: $1,046 to $1,192

Look first at the skew: the mean is about twice the median, because a few very large transactions pull it up. The 90th percentile is about $1,128, and the bootstrap says the true value is likely between about $1,046 and $1,192.

That range turns a guess into a decision the risk team can reason about. Setting the review threshold at the estimate, about $1,128, flags roughly 10% of transactions. Setting it at the top of the interval flags fewer, which means less review work but a bit more risk of letting a fraudulent large payment through. Setting it at the bottom flags more. The interval shows how much of that choice depends on sampling luck rather than on the real pattern of transactions. None of this was possible with the classical formula, which only handles means and proportions cleanly. This is the bootstrap earning its keep.

Key takeaways

Quick check

Six interview-style questions. The answers are one click away.

What's the difference between standard deviation and standard error?

The standard deviation measures how spread out individual values are. The standard error, s/√n, measures how much the sample mean would vary from sample to sample. More data shrinks the SE but not the SD: more people doesn't make people more alike, it just pins down their average better. To halve the SE you need four times the data.

In World War II, analysts studied bullet holes on bombers that returned from missions. Why would armouring the most-hit areas be a mistake?

Survivorship bias: the sample contains only planes that survived. The statistician Abraham Wald, of Columbia University's Statistical Research Group, worked on exactly this problem. Areas with few holes on returning planes may be where hits were fatal, so those planes never came back to be counted. Any sample that only includes "survivors", such as users who are still active, has the same blind spot.

200 users average 5.2 minutes per session, with s = 2.1. A PM insists the true average is 6 minutes. What do you say?

Build the interval: SE = 2.1/√200 ≈ 0.148, t* ≈ 1.97, so the 95% CI is about 4.91 to 5.49 minutes. 6 is well outside it, so the data doesn't support a 6-minute average. Day 12 turns this kind of reasoning into a formal hypothesis test.

One analyst builds a 95% interval from n = 100, another from n = 1,000. How do they compare?

Both should be centred near the true mean, but the n = 1,000 interval is about √10 ≈ 3.2 times narrower. Both are valid 95% intervals; the larger sample's is simply more useful, because it's more precise.

A survey of 500 users finds 68% like a new feature. Can you say most users like it?

SE = √(0.68 × 0.32/500) ≈ 0.021, so the 95% CI is about 63.9% to 72.1%. The whole range is above 50%, so yes, if the 500 were a random sample of users. If they were people who chose to answer a pop-up, the result describes keen responders, not all users.

Why does the bootstrap resample with replacement?

Resampling without replacement would just shuffle the same values, giving the identical statistic every time and no measure of uncertainty. With replacement, each resample is a different mix, about 63% of the original values with some repeated, which mimics drawing a fresh sample from the population.

Next up, Day 12 Hypothesis Testing End to End

From estimating to testing claims: null and alternative hypotheses, p-values, t-tests and z-tests, and the errors every test can make.