This is Module 4 of the Data Analyst to Data Scientist path, and the core of the change from analyst to data scientist. An analyst reports that the average order is 40.38. A data scientist reports that it is 40.38, and plausibly anywhere from about 31 to 49, and knows why that range matters before anyone makes a decision on it.

You’ll build: three short scripts: one that shows why sample averages move, one that puts a confidence interval around the shop’s average order, and one that tests whether customers in one country spend more.

You need: Python 3 and the CSV files from Module 2 (make_data.py creates them). No extra packages: everything here uses Python’s standard library.

1. Why an average moves: sampling variation

Your 13 orders are a sample of the orders the shop could have had. Another month, another 13 orders, another average. To see how much it moves, simulate a population where you know the true answer and draw many samples from it. Save this as sampling.py:

# How much does an average move from sample to sample? Simulate it.
import random
import statistics as st

random.seed(4)
# A made-up "true" population: 100,000 order values, skewed like real order data (many small, a few large).
population = [round(random.gammavariate(4, 10), 2) for _ in range(100_000)]
print(f"true average order: {st.mean(population):.2f}")

# Draw 1,000 samples of 13 orders each (the size of our shop data) and record each sample's average.
means = [st.mean(random.sample(population, 13)) for _ in range(1_000)]
print(f"sample averages range from {min(means):.2f} to {max(means):.2f}")
print(f"spread of the sample averages (standard deviation): {st.stdev(means):.2f}")

# The standard error formula predicts that spread from ONE sample: s / sqrt(n).
one = random.sample(population, 13)
print(f"one sample's estimate of that spread: {st.stdev(one) / 13 ** 0.5:.2f}")

Running it prints:

true average order: 40.08
sample averages range from 25.51 to 60.29
spread of the sample averages (standard deviation): 5.44
one sample's estimate of that spread: 5.32

Two lessons. First, with 13 orders the sample average can land anywhere from about 26 to 60 when the true value is 40. Second, you don’t need to draw a thousand samples to know this: the standard error, the sample’s standard deviation divided by the square root of its size, estimates the spread from a single sample (5.32 against the true 5.44). Quadrupling the sample size halves the standard error.

2. A confidence interval for the average order

Now the real data. Save this as interval.py:

# Average order value with a 95% confidence interval, two ways.
import csv
import random
import statistics as st

with open("orders.csv") as f:
    amounts = [float(row["amount"]) for row in csv.DictReader(f)]
n, mean, sd = len(amounts), st.mean(amounts), st.stdev(amounts)
se = sd / n ** 0.5
print(f"{n} orders, average {mean:.2f}, standard error {se:.2f}")

# 1. Formula: mean +/- t * SE. For 13 orders (12 degrees of freedom) t = 2.18; for large samples it is 1.96.
t = 2.18
print(f"t interval:         {mean - t * se:.2f} to {mean + t * se:.2f}")

# 2. Bootstrap: resample the 13 orders with replacement 10,000 times; keep the middle 95% of the averages.
random.seed(7)
boot = sorted(st.mean(random.choices(amounts, k=n)) for _ in range(10_000))
print(f"bootstrap interval: {boot[249]:.2f} to {boot[9749]:.2f}")

Running it prints:

13 orders, average 40.38, standard error 4.18
t interval:         31.28 to 49.49
bootstrap interval: 32.69 to 48.46

Both methods agree on the message: the average order is about 40, give or take 8 or 9. The t interval uses a formula; the value 2.18 comes from the t distribution, which is wider than the normal distribution’s 1.96 to allow for small samples (in Python, scipy.stats.t.ppf(0.975, 12)). The bootstrap makes no formula assumption: it treats your sample as a stand-in for the population and resamples it. With small or skewed data, it’s a useful second opinion.

How to say it in plain words: “Our average order was 40.38. Given how much orders vary and how few we have, the long-run average is plausibly between about 31 and 49.” Avoid “there is a 95% chance the true value is in this interval”: the procedure catches the true value in 95% of samples, but any single interval either contains it or doesn’t.

3. Testing a difference: a permutation test

A colleague notices that customers in Mexico (MX) seem to spend more per order. Is that a pattern or noise? Save this as permutation.py:

# Do customers in Mexico spend more per order than everyone else? A permutation test.
import csv
import random
import statistics as st

with open("customers.csv") as f:
    country = {row["customer_id"]: row["country"] for row in csv.DictReader(f)}
with open("orders.csv") as f:
    orders = [(country[row["customer_id"]], float(row["amount"])) for row in csv.DictReader(f)]

mx = [a for c, a in orders if c == "MX"]
rest = [a for c, a in orders if c != "MX"]
observed = st.mean(mx) - st.mean(rest)
print(f"MX average {st.mean(mx):.2f} ({len(mx)} orders), others {st.mean(rest):.2f} ({len(rest)} orders)")
print(f"observed difference: {observed:+.2f}")

# If country made no difference, the labels are arbitrary: shuffle them and see how often
# a difference at least this large appears by chance.
random.seed(11)
amounts = [a for _, a in orders]
extreme = 0
for _ in range(10_000):
    random.shuffle(amounts)
    diff = st.mean(amounts[:len(mx)]) - st.mean(amounts[len(mx):])
    if abs(diff) >= abs(observed):
        extreme += 1
print(f"p-value (two-sided): {extreme / 10_000:.2f}")

Running it prints:

MX average 43.33 (6 orders), others 37.86 (7 orders)
observed difference: +5.48
p-value (two-sided): 0.54

If country made no difference, shuffling the labels would produce a gap at least as large as 5.48 in about 54% of shuffles. A gap this size is entirely ordinary under chance, so the data don’t support the claim. They don’t refute it either: 13 orders can’t detect a difference this small. The honest answer is “we can’t tell yet; we’d need more orders.”

One caution about this data: several orders come from the same customer, so they aren’t fully independent. With real data, a better test shuffles customers rather than orders. With this little data the conclusion doesn’t change.

4. Reading p-values correctly

The American Statistical Association’s 2016 statement on p-values sets out six principles. Three of them prevent most mistakes in business analysis:

  • P-values do not measure the probability that the studied hypothesis is true, or the probability that the data were produced by random chance alone. A p-value of 0.54 doesn’t mean “54% chance there’s no difference”.
  • Decisions should not be based only on whether a p-value passes a threshold. A result at 0.049 and one at 0.051 carry almost the same evidence.
  • A p-value does not measure the size of an effect or the importance of a result. With enough data, a trivial difference becomes “significant”. Always report the size of the difference and its interval.

That’s why the habit this module builds is the interval, not the test: an estimate with its uncertainty answers both “how big?” and “how sure?”.

Checklist before you report a number

  • Does every key estimate come with a 95% interval or a margin of error?
  • Is the sample size stated?
  • For a difference, did you report its size, not only whether it is “significant”?
  • If the result isn’t significant, does the text say “can’t tell yet” rather than “no effect”?
  • Are the observations independent, or do some come from the same customer, store or day?

For the theory behind these tools, An Introduction to Statistical Learning (free, with editions in R and Python) covers standard errors, confidence intervals and hypothesis tests in the context of regression, which is where Module 6 picks them up.

Project: put an interval on a number your team reports

Take a metric your team reports every week or month, such as average order value, a conversion rate or a satisfaction score. Compute a 95% interval for its latest value with the bootstrap script, adapting the file and column names. Then write one paragraph: was last period’s change outside the range you’d expect from noise? If not, what would you stop saying about it?

Next: Module 5: Experiments That Give Trustworthy Answers: choosing a metric in advance, sizing a test and reading the result.