Descriptive statistics for marketers in Python: every number from the statistics chapter, rebuilt

TL;DR

Difficulty: Beginner

Every statistic a marketer needs takes one or two lines of Python. The work is in three habits around them.

  • Clean first and keep a ledger: in the example, refund rows alone pull the mean down by almost £6.
  • Name every default: NumPy, pandas and SciPy disagree on the standard deviation, skew, percentiles, z scores, the t test and the proportion interval.
  • Put the count, the median and an interval next to every mean, from one tested function.
  • Use Welch's t test, Wilson's interval for proportions and a bootstrap interval for small skewed groups.

My statistics chapter explains the numbers every marketer needs on an invented hamper shop. This chapter builds every one of them in Python, line by line, on data you generate yourself. Along the way it shows why two analysts running the same export through NumPy, pandas and SciPy can get different answers, and the habits that stop it.

The whale in the hamper basket, rebuilt in Python

Priya runs Northgate Hampers, an invented online hamper shop in Leeds at northgatehampers.example. Her dashboard says "average order value £102". The real orders say something else: 1,000 December orders, most of them between £40 and £100, and 20 corporate orders above £500 that carry a fifth of the revenue. Take those 20 out and the typical basket is £83, not £102.

That story, and every statistic in it, is explained in my Marketing Analytics chapter the statistics every marketer actually needs. Read it first if you have not: it explains what a median, a standard deviation, a confidence interval and a p value mean, and which decision each one changes. This chapter does not repeat the explanations. It builds them. Every number from that chapter, rebuilt line by line in Python with NumPy, pandas and SciPy, on data you generate yourself so you can run every block.

There is a second reason for this chapter, and it is the one I would put on a sticky note. Python does not compute "the" standard deviation. It computes a standard deviation, and which one depends on the library and its default. The same goes for skew, percentiles and z scores. Two analysts can run the same export through two tools, both get "the standard deviation", and disagree by 3%. On a small segment they can disagree by 12%. Nobody made a mistake. They used different defaults and never wrote them down. So the strongest habit in this chapter is a boring one: name the estimator, not just the statistic.

Northgate Hampers and all its numbers are invented, generated in code to resemble the example in the statistics chapter so you recognise every figure.

If you only read one section

This part is for the person who commissions the analysis and will never open a notebook.

  • Ask which average. If the mean and the median of order value differ by more than 20%, the report must show both, and name the orders that pull the mean up.
  • Ask for the defaults. A standard deviation, a skew or a percentile from Python should come with the method in writing (for example "sample standard deviation, n−1n - 1"). Without it, two reports on the same data will not match, and you will spend a meeting arguing about a rounding difference.
  • Ask for the cleaning ledger. Every report should show how many rows the export had, how many were removed at each step (test orders, staff orders, refund rows, other months) and what the mean was after each step. In the example below, cleaning moves the mean from £95.38 to £101.98.
  • Never accept a mean without its interval and its count. "£80 from 95 orders, interval £68 to £93" tells you to wait. "£80" alone tells you nothing.
  • A test that finds no difference is a result. When the honest answer is "not enough data yet", the report should say how many orders would settle it.

Everything below is the how. If you hire someone to do this, these five points are what to check.

Set up: three libraries and a fixed seed

You need Python with NumPy (fast arrays), pandas (tables) and SciPy (statistical functions). If you have not set them up yet, why Python for data analysis and how to set it up walks through it, and pandas Series and DataFrames explains the two table types used everywhere below. I ran every block on Python 3.14 with NumPy 2.4, pandas 2.3.3 and SciPy 1.16.3, the current releases in early January 2026. pandas 3.0 was in release candidate testing at the time (the first candidate appeared on 3 December 2025)1, bringing copy on write and a dedicated string type as defaults2. I also ran the code below against that candidate: the numbers come out the same.

The data comes from a random number generator with a fixed seed. A seed is a starting value. Give the generator the same seed and it produces the same "random" numbers every time, on every computer, so your output matches mine to the penny. NumPy's recommended way is np.random.default_rng(seed)3.

Example: generating Priya's 1,000 December orders

The statistics chapter shows a histogram of the 1,000 orders in eight value bands. I generate the orders band by band, with exactly those counts, and let the generator place each order at random inside its band. The £49 Classic hamper gets 120 orders at exactly £49, because a shop with fixed prices has many identical order values.

import numpy as np
import pandas as pd
from scipy import stats

print(np.__version__, pd.__version__)   # 2.4.0 2.3.3 when I wrote this
rng = np.random.default_rng(3424)

# (lowest, highest, number of orders) for each value band,
# the same counts as the histogram in the statistics chapter
bands = [(18, 40, 110), (40, 60, 290), (60, 80, 240), (80, 100, 150),
         (100, 150, 110), (150, 250, 55), (250, 500, 25)]

values = []
for low, high, count in bands:
    band = rng.uniform(low, high, count)
    if low == 40:
        band[:120] = 49.0          # the £49 Classic hamper, the bestseller
    values.append(band)
regular = np.round(np.concatenate(values), 2)
regular[0] = 18.0                  # one jar of chutney, the smallest order

# 20 corporate orders: 18 between £500 and £1,330,
# plus the Manchester practice (£1,500) and the Leeds law firm (£2,400)
corporate = np.round(rng.uniform(500, 1330, 18), 2)
corporate = np.concatenate([corporate, [1500.0, 2400.0]])

orders = pd.DataFrame({
    "order_id": np.arange(10001, 11001),
    "total": np.concatenate([regular, corporate]),
})
print(orders.shape)            # (1000, 2)
print(orders["total"].sum())   # 101984.33

Revenue is £101,984.33 from 1,000 orders. The statistics chapter rounds the same shop to £102,000. Close enough that every figure below lands where you expect it.

The same statistic, three answers: pin your defaults

Here is the trap that tutorials skip, and it is the one that causes the most wasted meetings.

The sample standard deviation divides the squared distances from the mean by n−1n - 1. The population standard deviation divides by nn. The statistics chapter explains why the sample version uses n−1n - 1: the mean was estimated from the same data, which uses up one "degree of freedom". In Python, the parameter that controls this is called ddof, short for delta degrees of freedom. The divisor is nn minus ddof.

And the defaults disagree:

  • pandas Series.std() uses ddof=1, the sample version4.
  • NumPy np.std() uses ddof=0, the population version5. Wes McKinney's book flags this in its table of array methods: the default denominator is nn6.
  • Python's built in statistics module has two functions, stdev for the sample and pstdev for the population7.

Skew has the same split. pandas Series.skew() returns the skew adjusted for sample size, which its documentation calls unbiased8. SciPy's stats.skew() returns the unadjusted version unless you pass bias=False9. Joanes and Gill compared the common skewness formulas and showed that they differ most in small samples10, which is exactly where marketers look: one campaign, one segment, one week.

Percentiles are worse, because there are at least nine reasonable definitions. Hyndman and Fan catalogued them in 199611, and NumPy's np.percentile lets you choose any of them with method, defaulting to "linear"12. pandas Series.quantile also defaults to linear interpolation13. Spreadsheets have their own split between inclusive and exclusive percentile functions, so a number copied from a sheet may follow a third definition.

On 1,000 orders these differences are small. On 20 orders they are not.

Example: the standard deviation, skew and 90th percentile of 20 corporate orders

Priya wants to know how the corporate orders vary, because she is thinking about a corporate price list. There are 20 of them.

corp = orders.loc[orders["total"] > 500, "total"]

print(corp.std())                        # 427.71  pandas Series: ddof=1
print(np.std(corp))                      # 416.88  NumPy function: ddof=0
print(corp.to_numpy().std(ddof=1))       # 427.71  NumPy, told to use n minus 1

import statistics
print(statistics.stdev(corp), statistics.pstdev(corp))   # 427.71 416.88

Notice the second line. corp is a pandas Series, yet np.std(corp) returns the NumPy answer, because the NumPy function passes its own default to the Series. The same object, two answers, decided by how you called it.

print(corp.skew())                       # 1.672  pandas: adjusted
print(stats.skew(corp))                  # 1.544  SciPy default: bias=True
print(stats.skew(corp, bias=False))      # 1.672  SciPy, adjusted: matches pandas

for method in ["linear", "hazen", "weibull", "nearest"]:
    print(method, np.percentile(corp, 90, method=method))
# linear  1319.64
# hazen   1399.80
# weibull 1479.96
# nearest 1299.60
StatisticAnswer AAnswer BGap
Standard deviation£427.71 (pandas, sample)£416.88 (NumPy default, population)2.6%
Skew1.672 (pandas, adjusted)1.544 (SciPy default)8%
90th percentile£1,319.64 (linear)£1,479.96 (Weibull)£160

A £160 gap in "the 90th percentile of corporate orders" is a different price list. Neither number is wrong. They answer the question with different rules.

The rule I use, and the one I would put in any team's notebook template: always write the parameter, even when it equals the default. x.std(ddof=1), stats.skew(x, bias=False), x.quantile(0.9, interpolation="linear"). It costs a few characters and it turns a silent assumption into a visible one. Below I keep the pandas defaults for readability, and say so.

Clean before you describe, and keep a ledger

Descriptive statistics are only as good as the rows you feed them, and shop exports are never clean. The order export from a typical shop has four traps, all of which move the mean:

  • Test orders, often £0.01 or £1, placed by whoever set up the payment provider.
  • Staff orders, at staff prices.
  • Refunds as separate rows with negative totals. A refund is not an order. Leave it in and it inflates the count and drags the mean down.
  • Timestamps in UTC (Coordinated Universal Time) rather than shop time. A "December" filter on UTC dates puts orders on the wrong side of midnight whenever the shop's clock is not on UTC.

The full toolkit for cleaning is in cleaning data in pandas, and time zones are covered properly in time series in pandas. Here I add one habit: a cleaning ledger. After every step, record the row count, the mean and the median. The ledger is the paper trail that lets someone else check your work, and it shows at a glance which step mattered.

Example: from 1,044 raw rows to 1,000 December orders

First I build the kind of export Priya's shop actually produces: her 1,000 orders with UTC timestamps, six orders from the first hour of New Year's Day, three test orders, four staff orders and 31 refund rows.

local_tz = "Europe/London"
rng_mess = np.random.default_rng(7)

# when each December order was placed, in shop time
seconds = rng_mess.uniform(0, 31 * 24 * 3600, len(orders))
placed = pd.Timestamp("2025-12-01", tz=local_tz) + pd.to_timedelta(seconds, unit="s")

export = orders.assign(
    created_at=placed.tz_convert("UTC"),   # the export stores UTC
    email="customer@example.com",
    kind="order",
)

# six New Year orders, placed in the first hour of 1 January, shop time
new_year = pd.DataFrame({
    "order_id": np.arange(11001, 11007),
    "total": [49.0, 62.5, 38.0, 71.2, 49.0, 55.9],
    "created_at": (pd.Timestamp("2026-01-01 00:05", tz=local_tz)
                   + pd.to_timedelta([0, 9, 17, 26, 38, 51], unit="min")).tz_convert("UTC"),
    "email": "customer@example.com",
    "kind": "order",
})

# three test orders and four staff orders
noise = pd.DataFrame({
    "order_id": np.arange(11007, 11014),
    "total": [0.01, 0.01, 1.00, 24.50, 31.00, 18.75, 42.00],
    "created_at": pd.Timestamp("2025-12-03 10:00", tz="UTC"),
    "email": ["test@northgatehampers.example"] * 3 + ["staff@northgatehampers.example"] * 4,
    "kind": "order",
})

# 31 refunds, each a separate row with a negative total
refunded = orders.sample(31, random_state=1)
refunds = pd.DataFrame({
    "order_id": refunded["order_id"].to_numpy(),
    "total": -refunded["total"].to_numpy(),
    "created_at": pd.Timestamp("2025-12-28 09:00", tz="UTC"),
    "email": "customer@example.com",
    "kind": "refund",
})

raw = pd.concat([export, new_year, noise, refunds], ignore_index=True)
print(len(raw))   # 1044

Now the cleaning, with the ledger built as I go:

def ledger_row(step, frame):
    return {"step": step, "rows": len(frame),
            "mean": round(frame["total"].mean(), 2),
            "median": round(frame["total"].median(), 2)}

is_internal = raw["email"].str.endswith("@northgatehampers.example")
is_refund = raw["kind"].eq("refund")

clean = raw.loc[~is_internal & ~is_refund].copy()
clean["placed_local"] = clean["created_at"].dt.tz_convert(local_tz)
in_december = clean["placed_local"].between(
    pd.Timestamp("2025-12-01", tz=local_tz),
    pd.Timestamp("2026-01-01", tz=local_tz),
    inclusive="left",
)
december = clean.loc[in_december]

ledger = pd.DataFrame([
    ledger_row("raw export", raw),
    ledger_row("without test and staff orders", raw.loc[~is_internal]),
    ledger_row("without refund rows", clean),
    ledger_row("December in shop time", december),
])
print(ledger.to_string(index=False))
StepRowsMeanMedian
Raw export1,044£95.38£66.25
Without test and staff orders1,037£95.91£66.41
Without refund rows1,006£101.70£67.97
December in shop time1,000£101.98£68.09

Read it top to bottom. The refund rows are the step that matters: 31 negative rows pulled the mean down by almost £6. The refunds themselves, £2,849.82 in total, do not vanish. They go into their own table, and you net them against their orders by order_id when the question is net revenue rather than basket size.

The time zone step removed the six New Year orders. In December, London is on Greenwich Mean Time, which equals UTC, so a filter on the UTC date would have given the same 1,000 rows here:

naive = clean.loc[clean["created_at"].dt.strftime("%Y-%m") == "2025-12"]
print(len(naive))   # 1000, the same in winter

Run the same filter on a summer month and every order between midnight and 1am British Summer Time lands on the previous day. Convert to shop time anyway, every time, so the code is right in July as well as in December.

The flow below is the order I follow on every export.

Tap or click to enlarge

From here on I work with the clean orders table, which holds exactly the 1,000 December orders.

Three averages in pandas

The mean adds everything and divides by the count. The median is the middle value after sorting. The mode is the most frequent value. The statistics chapter explains why they disagree in a shop with a long tail, and Foundations: the mean and Foundations: the median and the mode build them from scratch.

xˉ=1n∑i=1nxi\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i

Here xˉ\bar{x} is the mean order value, nn the number of orders, xix_i the value of order ii, and ∑\sum adds them all up. With Priya's numbers: 101,984.33/1,000=£101.98101{,}984.33 / 1{,}000 = £101.98.

Example: mean, median and mode of the December orders

x = orders["total"]
print(x.mean(), x.median())   # 101.98 68.09

print(x.mode())               # 0    49.0
print(x.value_counts().head(1))
# total
# 49.0    120

Mean £101.98, median £68.09, mode £49. The same three numbers as the statistics chapter, in the same order: mean highest, mode lowest, which is the signature of a distribution skewed to the right14.

Two Python details. First, mode() returns a Series, not a number, because a set of values can have several modes. Take .iloc[0] if you want one. Second, the mode only means something when values repeat. Here 120 orders sit at exactly £49 because the Classic has a fixed price. On values with pence scattered everywhere, every value appears once and the "mode" is just the smallest number. Round first (x.round(0).mode()) or bin the values, or leave the mode out.

describe() gives most of this in one call, and McKinney's book introduces it in exactly that role6:

print(x.describe().round(2))
# count    1000.00
# mean      101.98
# std       158.09
# min        18.00
# 25%        49.00
# 50%        68.09
# 75%        94.03
# max      2400.00

It is a fine first look. Note what it leaves out: the mode, the skew, the share of revenue in the tail and any interval. I build a better version further down.

Spread: variance, standard deviation and the coefficient of variation

The variance is the average squared distance from the mean, the standard deviation is its square root, and the coefficient of variation puts the spread in proportion to the mean. All three are built up in Foundations: spread.

s=1n−1∑i=1n(xi−xˉ)2,CV=sxˉs = \sqrt{\frac{1}{n-1}\sum_{i=1}^{n}(x_i - \bar{x})^2}, \qquad CV = \frac{s}{\bar{x}}

Here ss is the sample standard deviation in pounds, xi−xˉx_i - \bar{x} is the distance of order ii from the mean xˉ\bar{x}, n−1n - 1 is the divisor that pandas uses by default (ddof=1), and CVCV is the coefficient of variation, which has no unit.

Example: how spread out Priya's orders are

print(round(x.var(), 1))                # 24991.3  pounds squared
print(round(x.std(), 2))                # 158.09
print(round(x.std() / x.mean(), 2))     # 1.55

The variance, 24,991, is in pounds squared, which nobody can picture. The standard deviation brings it back to pounds: £158.09, bigger than the mean itself. The coefficient of variation is 158.09/101.98=1.55158.09 / 101.98 = 1.55. The statistics chapter's rule: above 1, do not trust the mean alone. With 1,000 orders the choice between ddof=1 and ddof=0 changes the standard deviation by only 0.05%, but write it down anyway. The next segment you analyse may have 20 rows.

Skew: one number for the long tail

Mean, median and mode tell you the distribution leans. Skewness puts a number on how far. pandas computes the adjusted Fisher Pearson coefficient:

G1=n(n−1)n−2⋅1n∑i=1n(xi−xˉ)3(1n∑i=1n(xi−xˉ)2)3/2G_1 = \frac{\sqrt{n(n-1)}}{n-2}\cdot\frac{\frac{1}{n}\sum_{i=1}^{n}(x_i-\bar{x})^3}{\left(\frac{1}{n}\sum_{i=1}^{n}(x_i-\bar{x})^2\right)^{3/2}}

Here G1G_1 is the sample skewness, the large fraction on the right is the average cubed distance from the mean divided by the spread cubed, and the factor n(n−1)/(n−2)\sqrt{n(n-1)}/(n-2) is the small sample adjustment that SciPy leaves out by default. Spread and its square, the variance, are in Foundations: spread. Cubing keeps the sign, so a long tail of large orders gives a positive skew. A symmetric bell has a skew of 0. The further from 0, the longer the tail.

Example: skew with and without the corporate orders

print(round(x.skew(), 2))                    # 7.24  pandas, adjusted
print(round(stats.skew(x), 2))               # 7.23  SciPy default, bias=True
print(round(x[x <= 500].skew(), 2))          # 3.22  without the 20 corporate orders
print(round(np.log(x).skew(), 2))            # 1.41  on the log scale

A skew of 7.24 is extreme. Drop the 20 corporate orders and it is still 3.22, because even the gift shop has a tail of £150 to £500 orders. Take the logarithm of each order value and the skew falls to 1.41. That is why later chapters model the logarithm of order value rather than the value itself: on the log scale, money behaves more like the bell curve the textbook methods assume. The price elasticity chapter of this series, out in February, does exactly that.

Percentiles answer threshold questions

A percentile is the value below which a given share of the data falls. The median is the 50th percentile. The 25th and 75th are the quartiles. Percentiles are what you want whenever the business question has a threshold in it: free delivery, a loyalty tier, a fraud check, a "big order" alert.

Example: where to put free delivery

The statistics chapter asks whether Priya's free delivery threshold should sit at £60 or £90. Two lines answer the first half of that question: where the orders are, and what share of them already clears each candidate threshold.

print(x.quantile([0.10, 0.25, 0.50, 0.75, 0.90, 0.98]).round(2))
# 0.10     37.80
# 0.25     49.00
# 0.50     68.09
# 0.75     94.03
# 0.90    150.02
# 0.98    493.62

for threshold in [60, 75, 90]:
    print(threshold, round((x >= threshold).mean(), 3))
# 60 0.6
# 75 0.412
# 90 0.285

(x >= threshold) gives a column of True and False, and the mean of True and False is the share of True, because Python counts True as 1. At £60, 60% of orders already qualify, so free delivery there gives away shipping on most baskets and nudges few. At £90, only 28.5% qualify, and the orders between about £60 and £90 are the ones a threshold could push upwards. The interquartile range, £49 to £94, is where the typical customer lives. The data cannot tell you which threshold makes more money, that needs a test, but it tells you which one can change behaviour.

For the reverse question, "what percentile is a £120 order?", SciPy has percentileofscore:

print(stats.percentileofscore(x, 120, kind="weak"))   # 84.6

A £120 order is bigger than 84.6% of December orders. That sentence is far more useful to a marketer than "it is 0.12 standard deviations above the mean", which is where the next sections go.

A histogram before any statistic

The statistics chapter's first check is to plot the distribution before computing anything, because your eye catches test orders, currency mixups and duplicated rows faster than any number. In pandas, pd.cut puts each order into a band, and value_counts(sort=False) counts the bands in order.

Example: the eight bands from the statistics chapter

edges = [0, 40, 60, 80, 100, 150, 250, 500, np.inf]
labels = ["under 40", "40 to 60", "60 to 80", "80 to 100",
          "100 to 150", "150 to 250", "250 to 500", "over 500"]
counts = pd.cut(x, bins=edges, labels=labels, right=False).value_counts(sort=False)
print(counts.tolist())   # [110, 290, 240, 150, 110, 55, 25, 20]

right=False makes each band include its lower edge and exclude its upper one, so an order of exactly £60 lands in "60 to 80". The counts match the statistics chapter exactly, because I generated them that way.

Invented example data generated in Python. 110 orders under £40, 290 between £40 and £60, 240 between £60 and £80, 150 between £80 and £100, 110 between £100 and £150, 55 between £150 and £250, 25 between £250 and £500 and 20 over £500. The bands are unequal in width. Tap or click to enlarge

To draw it yourself in matplotlib:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(counts.index.astype(str), counts.to_numpy(), color="#ec4899")
ax.set_title("Most December orders sit between £40 and £100")
ax.set_xlabel("Order value in £")
ax.set_ylabel("Orders")
ax.tick_params(axis="x", labelrotation=45)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig("orders_by_value.png", dpi=200)

The title states the finding rather than the topic. Why that matters, and when a box plot or a density works better than bars, is the subject of showing distributions honestly in my data storytelling series. The mechanics of matplotlib, seaborn and plotly are in charts in Python.

One function for the first table of every report

The statistics chapter ends its section on spread with the summary table it would put on the first page of any eCommerce report. In Python that table should be a function, written once, tested once and used on every export, every channel and every segment. Then nobody recomputes it by hand with different defaults. How to keep such a function in a module with a test next to it is the subject of a reproducible Python analysis workflow.

Example: describe_orders on the December orders

def describe_orders(values, whale_at=500):
    """The first table of any order report: centre, spread, shape and whales."""
    v = pd.Series(values, dtype="float64").dropna()
    whales = v[v > whale_at]
    return pd.Series({
        "orders": len(v),
        "mean": v.mean(),
        "median": v.median(),
        "mode": v.round(0).mode().iloc[0],
        "std": v.std(ddof=1),
        "cv": v.std(ddof=1) / v.mean(),
        "skew": v.skew(),                      # adjusted, as SciPy with bias=False
        "p10": v.quantile(0.10, interpolation="linear"),
        "p90": v.quantile(0.90, interpolation="linear"),
        "min": v.min(),
        "max": v.max(),
        "whales": len(whales),
        "whale_share_of_revenue": whales.sum() / v.sum(),
        "mean_without_whales": v[v <= whale_at].mean(),
        "se_mean": v.std(ddof=1) / np.sqrt(len(v)),
    }).round(2)

print(describe_orders(orders["total"]))
MeasureValueWhat it tells you
Orders1,000The sample size, always first
Mean£101.98Revenue per order
Median£68.09What a typical customer spends
Mode£49The bestseller's price
Standard deviation£158.09Spread, larger than the mean
Coefficient of variation1.55Above 1: do not trust the mean alone
Skew7.24A very long right tail
10th and 90th percentile£37.80 and £150.02Where 80% of orders sit
Minimum and maximum£18 and £2,400The chutney jar and the Leeds law firm
Orders above £50020About 20% of revenue
Mean without them£83.02The gift shop on its own
Standard error of the mean£5.00How precise the mean is

Every number from the statistics chapter's table, plus skew, percentiles and the standard error, from one call. The whale_at parameter makes the threshold an explicit decision rather than a buried constant, which is the statistics chapter's last check: decide in writing whether the large orders belong in the analysis. Run it with the whales in and out and print both.

Because describe_orders returns a Series, it works with a group by: orders.groupby("channel")["total"].apply(describe_orders).unstack() gives one row per channel. The mechanics of that are in group by and pivot tables in pandas.

z scores: place one customer, not one order

A z score says how many standard deviations a value sits above or below the mean. It is explained with the bell curve in Foundations: distributions.

z=x−xˉsz = \frac{x - \bar{x}}{s}

Here xx is the value you are looking at, xˉ\bar{x} the mean and ss the standard deviation of the group it belongs to.

The z score is only meaningful when the distribution is roughly symmetric. For newsletter opens, pages per visit or the logarithm of order value it works. For order value in pounds it does not, as the example shows.

Example: the keen newsletter reader, and the £2,400 order

For this and the correlation section I generate 640 newsletter customers, as in the statistics chapter, with columns for opens, repeat orders, discount depth and order values. Each pair of columns is drawn from a helper that produces two linked normal variables with a chosen correlation, then turned into counts or pounds.

rng_cust = np.random.default_rng(12155)
n = 640

def correlated_pair(rng, n, rho):
    """Two standard normal columns with correlation rho."""
    a = rng.standard_normal(n)
    b = rho * a + np.sqrt(1 - rho**2) * rng.standard_normal(n)
    return a, b

a, b = correlated_pair(rng_cust, n, 0.36)
opens = np.clip(np.round(6 + 4 * a), 0, None)
repeat_orders = np.clip(np.round(1 + 1.2 * b), 0, None)

a, b = correlated_pair(rng_cust, n, -0.45)
discount_pct = np.clip(np.round(10 + 6 * a), 0, 30)
order_value = np.round(np.exp(4.2 + 0.4 * b), 2)

a, b = correlated_pair(rng_cust, n, 0.08)
pages_per_session = np.round(np.exp(1.4 + 0.4 * a), 1)
value_same_visit = np.round(np.exp(4.2 + 0.4 * b), 2)

a, b = correlated_pair(rng_cust, n, 0.58)
first_order = np.round(np.exp(4.1 + 0.5 * a), 2)
second_order = np.round(np.exp(4.1 + 0.5 * b), 2)

customers = pd.DataFrame({
    "opens": opens, "repeat_orders": repeat_orders,
    "discount_pct": discount_pct, "order_value": order_value,
    "pages_per_session": pages_per_session, "value_same_visit": value_same_visit,
    "first_order": first_order, "second_order": second_order,
})
print(customers["opens"].agg(["mean", "std"]).round(2))   # mean 5.97, std 3.89

The statistics chapter's subscriber opened 15 newsletters, against a mean of 6 and a standard deviation of 4. In the generated data the mean is 5.97 and the standard deviation 3.89:

opens_mean = customers["opens"].mean()
opens_sd = customers["opens"].std()
print(round((15 - opens_mean) / opens_sd, 2))     # 2.32

customers["opens_z"] = (customers["opens"] - opens_mean) / opens_sd
print((customers["opens_z"] > 2).sum())           # 24

z=(15−5.97)/3.89=2.32z = (15 - 5.97) / 3.89 = 2.32, close to the chapter's 2.25. Twenty four of the 640 subscribers sit more than two standard deviations above the mean. That is a list worth giving to whoever writes the newsletter.

SciPy has stats.zscore, but it divides by the population standard deviation, ddof=0, unless you tell it otherwise15. On 640 rows the difference is in the third decimal (3.871 against 3.868 for the keenest reader). On a 30 row segment it is not. Either pass ddof=1 or compute it yourself as above.

Now try the same on money:

z_whale = (2400 - x.mean()) / x.std()
print(round(z_whale, 1))           # 14.5
print(stats.norm.sf(z_whale))      # 3.6e-48  what a bell curve would expect
print((x >= 2400).mean())          # 0.001    what actually happened

On a bell curve, an order 14.5 standard deviations above the mean would be a chance of about 4 in 104810^{48}, a number with 47 zeros after the decimal point. In Priya's shop it is one order in a thousand, a law firm's Christmas list. The z score is not wrong, the bell curve is the wrong ruler for money. For order values, use percentile ranks, as in the free delivery example, or z scores on the log scale.

The standard error, simulated instead of believed

The standard error of the mean is the standard deviation of the orders divided by the square root of their count:

SE=snSE = \frac{s}{\sqrt{n}}

Here SESE is the standard error, ss the standard deviation of individual orders and nn the number of orders. It is built up in Foundations: sampling. The statistics chapter explains why it works on skewed data: by the central limit theorem, the means of many samples are roughly normal even when the individual values are not16. It also warns that skewed data needs more than the classroom rule of 30.

In Python you do not have to take either claim on trust. You can simulate them. Draw many samples from Priya's orders, compute each sample's mean, and look at how those means are distributed. Drawing with replacement from your own data like this is called resampling, and it is the idea behind the bootstrap below.

Example: resampling the December orders 10,000 times

sim = np.random.default_rng(42)
s = x.std()
rows = []
for size in [30, 100, 400, 1600]:
    means = sim.choice(x.to_numpy(), size=(10_000, size), replace=True).mean(axis=1)
    rows.append({
        "orders_per_sample": size,
        "se_formula": s / np.sqrt(size),
        "se_simulated": means.std(ddof=1),
        "skew_of_means": stats.skew(means, bias=False),
    })
print(pd.DataFrame(rows).round(2))
#    orders_per_sample  se_formula  se_simulated  skew_of_means
# 0                 30       28.86         28.52           1.29
# 1                100       15.81         15.80           0.70
# 2                400        7.90          7.89           0.39
# 3               1600        3.95          3.94           0.15

sim.choice(..., size=(10_000, size)) draws 10,000 samples at once as rows of a matrix, and .mean(axis=1) averages each row. That is NumPy's vectorisation at work, explained in NumPy explained.

Two findings. First, the formula is right: the simulated spread of the means matches s/ns / \sqrt{n} almost exactly at every size.

Invented example. Standard error of the mean order value at Northgate Hampers by sample size. Formula: £28.86 at 30 orders, £15.81 at 100, £7.90 at 400 and £3.95 at 1,600. Simulated from 10,000 resamples: £28.52, £15.80, £7.89 and £3.94. The two lines lie almost on top of each other. Tap or click to enlarge

Second, the central limit theorem needs more than 30 orders here. With samples of 30, the sample means are still clearly skewed, 1.29, which is more skew than most textbook examples of skewed data. At 100 orders it is 0.70, at 400 it is 0.39, and only around 1,600 orders does the distribution of the mean look like a bell. With data as skewed as order values, a mean from a few dozen orders is shaky and an interval built on the normal curve will be too optimistic on one side.

Invented example. Skew of 10,000 simulated sample means of Northgate Hampers order values: 1.29 with 30 orders per sample, 0.70 with 100, 0.39 with 400 and 0.15 with 1,600. A perfect bell curve has a skew of 0. Tap or click to enlarge

A confidence interval for a mean

A 95% confidence interval for a mean is the mean plus or minus a multiplier times the standard error. With the standard deviation estimated from the data, the multiplier comes from the t distribution, which has heavier tails than the normal curve for small samples17. The idea is explained in Foundations: confidence intervals.

xˉ±t0.975, ‘n−1‘×sn\bar{x} \pm t_{0.975,\,`n-1`} \times \frac{s}{\sqrt{n}}

Here xˉ\bar{x} is the mean, s/ns/\sqrt{n} the standard error, and t0.975, n−1t_{0.975,\,n-1} the value that cuts off the top 2.5% of a t distribution with n−1n - 1 degrees of freedom. For 1,000 orders it is 1.962, nearly the normal curve's 1.96.

Example: £102 with its interval

n_orders = len(x)
se = x.sem()                                   # std / sqrt(n), ddof=1
t_mult = stats.t.ppf(0.975, df=n_orders - 1)
print(round(se, 2), round(t_mult, 3))          # 5.0 1.962
print(x.mean() - t_mult * se, x.mean() + t_mult * se)   # 92.17 111.79

101.98±1.962×5.00101.98 \pm 1.962 \times 5.00, so £92.17 to £111.79. The statistics chapter has £92.20 to £111.80. stats.t.interval(0.95, df=n_orders - 1, loc=x.mean(), scale=se) gives the same two numbers in one call.

Example: the three campaigns in one group by

The statistics chapter's real decision was about two Meta campaigns and the newsletter. I generate their November orders with the same counts and close to the same means and spreads. "Treat Yourself" has 88 single hamper orders and seven orders where someone bought two to four hampers at once.

rng_camp = np.random.default_rng(12057)

family = 20 + rng_camp.lognormal(np.log(42), 0.65, 180)
singles = 15 + rng_camp.lognormal(np.log(43), 0.55, 88)
hampers = rng_camp.integers(2, 5, 7)                  # 2 to 4 hampers in one order
multis = hampers * rng_camp.uniform(60, 85, 7)
newsletter = 15 + rng_camp.lognormal(np.log(48), 0.58, 240)

campaigns = pd.DataFrame({
    "channel": ["Family Christmas (Meta)"] * 180
             + ["Treat Yourself (Meta)"] * 95
             + ["Newsletter (owned)"] * 240,
    "total": np.round(np.concatenate([family, singles, multis, newsletter]), 2),
    "hampers": np.concatenate([np.ones(180), np.ones(88), hampers, np.ones(240)]).astype(int),
})

A lognormal draw is a value whose logarithm is normally distributed: always positive, with a long right tail, which is why it is the usual stand in for order values. Now the whole table from the statistics chapter, intervals included, in one group by:

table = (campaigns.groupby("channel", sort=False)["total"]
         .agg(orders="count", mean="mean", median="median", std="std", se="sem"))
t_mult = stats.t.ppf(0.975, df=table["orders"] - 1)
table["ci_low"] = table["mean"] - t_mult * table["se"]
table["ci_high"] = table["mean"] + t_mult * table["se"]
print(table.round(2))
ChannelOrdersMeanMedianStandard deviationStandard error95% interval
Family Christmas (Meta)180£73.46£61.66£38.39£2.86£67.81 to £79.10
Treat Yourself (Meta)95£80.44£59.31£61.38£6.30£67.94 to £92.94
Newsletter (owned)240£68.47£64.03£30.70£1.98£64.57 to £72.38

stats.t.ppf accepts a whole column of degrees of freedom, so each channel gets its own multiplier. The reading is the statistics chapter's: Treat Yourself has the highest mean but the lowest median, and its interval is more than twice as wide as Family Christmas's. The two intervals overlap almost completely.

When the data are skewed, ask the bootstrap

The t interval is symmetric by construction: the same distance below the mean as above. For 95 skewed orders that is suspicious, because the simulation showed that the mean of a small skewed sample is itself skewed. The bootstrap builds the interval from the data instead of from a formula: resample the 95 orders thousands of times, compute the mean each time, and read the interval off the resampled means. SciPy's stats.bootstrap does this, and by default uses the BCa method (bias corrected and accelerated), which adjusts for skew18.

Example: a bootstrap interval for Treat Yourself

treat = campaigns.loc[campaigns["channel"].str.startswith("Treat"), "total"]
boot = stats.bootstrap((treat.to_numpy(),), np.mean, confidence_level=0.95,
                       method="BCa", rng=np.random.default_rng(1))
print(boot.confidence_interval)   # low 70.12, high 96.15

Note the data goes in as a tuple, (treat.to_numpy(),), because bootstrap accepts several samples. The BCa interval runs from £70.12 to £96.15, against £67.94 to £92.94 from the t formula. It is shifted upwards and stretched on the high side, because a few multi hamper orders can push a resampled mean up much further than anything can pull it down. For a campaign with fewer than a few hundred skewed orders, I report the bootstrap interval and mention the t interval in a footnote, not the other way round.

A confidence interval for a proportion

Many marketing numbers are proportions, not means: conversion rate, the share of repeat customers, the share of orders above a threshold. The textbook interval for a proportion, p^±1.96p^(1−p^)/n\hat{p} \pm 1.96\sqrt{\hat{p}(1-\hat{p})/n}, is called the Wald interval. It is easy, and it is unreliable: Brown, Cai and DasGupta showed that its actual coverage falls well short of 95% even for fairly large samples, and recommended the Wilson interval, among others, instead19. Wilson published it in 192720.

p^+z22n1+z2n±z1+z2np^(1−p^)n+z24n2\frac{\hat{p} + \frac{z^2}{2n}}{1 + \frac{z^2}{n}} \pm \frac{z}{1 + \frac{z^2}{n}}\sqrt{\frac{\hat{p}(1-\hat{p})}{n} + \frac{z^2}{4n^2}}

Here p^\hat{p} is the observed proportion, nn the number of trials (orders, visitors, customers) and zz the normal multiplier, 1.96 for 95%. The interval is pulled slightly towards one half, which is what keeps it inside 0 and 1. The ideas behind it are in Foundations: probability.

Example: multi hamper orders in Treat Yourself

Seven of the 95 Treat Yourself orders contained more than one hamper. Priya wants to know whether "buy several" is a real behaviour worth a bundle offer.

multi = campaigns.loc[campaigns["channel"].str.startswith("Treat"), "hampers"] > 1
k, n_treat = int(multi.sum()), len(multi)
p_hat = k / n_treat

se_wald = np.sqrt(p_hat * (1 - p_hat) / n_treat)
print(round(p_hat, 3), round(p_hat - 1.96 * se_wald, 3), round(p_hat + 1.96 * se_wald, 3))
# 0.074 0.021 0.126

ci = stats.binomtest(k, n_treat).proportion_ci(confidence_level=0.95, method="wilson")
print(round(ci.low, 3), round(ci.high, 3))   # 0.036 0.144

By hand, with p^=7/95=0.0737\hat{p} = 7/95 = 0.0737 and z2=3.84z^2 = 3.84: the centre is (0.0737+0.0202)/1.0404=0.0902(0.0737 + 0.0202) / 1.0404 = 0.0902, and the half width is 1.8838×0.000718+0.000106=0.05411.8838 \times \sqrt{0.000718 + 0.000106} = 0.0541. So 3.6% to 14.4%, against the Wald interval's 2.1% to 12.6%. Note that the Wilson interval is not centred on 7.4%. SciPy's binomtest offers "exact" (Clopper Pearson), "wilson" and "wilsoncc", and its default is exact, not Wilson21. Another default worth writing down.

The difference becomes embarrassing with small counts. One order in 20:

p_small = 1 / 20
se_small = np.sqrt(p_small * (1 - p_small) / 20)
print(p_small - 1.96 * se_small, p_small + 1.96 * se_small)   # -0.046 0.146
small = stats.binomtest(1, 20).proportion_ci(method="wilson")
print(small.low, small.high)                                  # 0.009 0.236

The Wald interval goes below zero, a negative share of orders. The Wilson interval runs from 0.9% to 23.6%, which is honest: with 20 orders you know almost nothing about a rare behaviour.

A t test for the £7 gap

The agency said Treat Yourself delivered a £7 higher basket. The statistics chapter tests that by hand with a z score and gets a p value of about 0.31. In Python the standard tool is a two sample t test, stats.ttest_ind. The method is explained in Foundations: hypothesis tests.

One more default to pin. ttest_ind assumes both groups have the same variance unless you pass equal_var=False22. That default is Student's original test. With equal_var set to False you get Welch's t test, which drops the assumption23. Our two campaigns have standard deviations of £38 and £61, so the assumption is plainly false. Delacre, Lakens and Leys argue that Welch's test should be the default in any case, because it loses almost nothing when variances are equal and protects you when they are not24.

t=xˉ1−xˉ2s12n1+s22n2t = \frac{\bar{x}_1 - \bar{x}_2}{\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}}

Here xˉ1\bar{x}_1 and xˉ2\bar{x}_2 are the two campaign means, s1s_1 and s2s_2 their standard deviations and n1n_1 and n2n_2 their order counts. The bottom line is the standard error of the difference, the same quantity the statistics chapter computes by hand. The logic of the test is in Foundations: hypothesis tests.

Example: Welch's t test on the two Meta campaigns

family_tot = campaigns.loc[campaigns["channel"].str.startswith("Family"), "total"]

welch = stats.ttest_ind(treat, family_tot, equal_var=False)
student = stats.ttest_ind(treat, family_tot)          # default: equal variances assumed

print(round(treat.mean() - family_tot.mean(), 2))                  # 6.98
print(round(welch.statistic, 2), round(welch.pvalue, 3), round(welch.df, 1))
# 1.01 0.315 133.8
print(round(student.statistic, 2), round(student.pvalue, 3))       # 1.16 0.248
print(welch.confidence_interval(0.95))                             # low -6.70, high 20.66

By hand: the standard error of the difference is 61.382/95+38.392/180=39.66+8.19=6.92\sqrt{61.38^2/95 + 38.39^2/180} = \sqrt{39.66 + 8.19} = 6.92, and t=6.98/6.92=1.01t = 6.98 / 6.92 = 1.01. The Welch p value is 0.315, the statistics chapter's 0.31. If the two campaigns truly produced the same basket, a gap this large would turn up about one time in three. The 95% interval for the gap runs from minus £6.70 to plus £20.66: Treat Yourself could be worse, the same or much better. That is not evidence, and the American Statistical Association's statement on p values says why you should not read more into it25.

Student's version, with the false equal variance assumption, gives 0.248. Still nothing, but closer to a number someone might wave around. That is the practical risk of the default: it makes noisy differences look more convincing when the smaller group is the more variable one, which in marketing it usually is.

How many orders would settle it

The statistics chapter computes how many orders per campaign would detect a genuine £7 gap at the usual 5% significance level and 80% power. The details are in Foundations: sample size.

n=(z1−α/2+z1−β)2 (s12+s22)Δ2n = \frac{(z_{1-\alpha/2} + z_{1-\beta})^2\,(s_1^2 + s_2^2)}{\Delta^2}

Here nn is the orders needed per campaign, z1−α/2=1.96z_{1-\alpha/2} = 1.96 for a 5% two sided test, z1−β=0.84z_{1-\beta} = 0.84 for 80% power, s1s_1 and s2s_2 the two standard deviations, and Δ\Delta the gap you want to detect, £7.

alpha, power, gap = 0.05, 0.80, 7.0
z_a = stats.norm.ppf(1 - alpha / 2)      # 1.96
z_b = stats.norm.ppf(power)              # 0.84
n_needed = (z_a + z_b) ** 2 * (family_tot.var() + treat.var()) / gap**2
print(int(np.ceil(n_needed)))            # 840

About 840 orders per campaign with the generated spreads, the statistics chapter's "about 830" with its rounded ones. Treat Yourself had 95. The decision memo writes itself: no detectable difference, decide on cost per order, or run both until each has around 840 orders. The A/B testing chapter of this series, due in August, builds the full version with power curves.

Correlation in pandas and SciPy

Pearson's correlation coefficient rr measures how closely two variables move together along a straight line, from minus 1 to plus 1. Spearman's coefficient does the same on the ranks of the values, so it catches any steady rise or fall, straight or curved, and a single extreme value cannot dominate it. Both are explained, with the causation trap, in the statistics chapter and in Foundations: correlation.

pandas gives you Series.corr and DataFrame.corr (Pearson by default, method="spearman" for ranks). SciPy's stats.pearsonr adds a p value and, through .confidence_interval(), an interval for rr itself26.

Example: four correlations among 640 newsletter customers

pairs = [("opens", "repeat_orders"), ("discount_pct", "order_value"),
         ("pages_per_session", "value_same_visit"), ("first_order", "second_order")]
rows = []
for a_col, b_col in pairs:
    res = stats.pearsonr(customers[a_col], customers[b_col])
    ci = res.confidence_interval(0.95)
    rows.append({"pair": f"{a_col} and {b_col}", "r": res.statistic,
                 "r_squared": res.statistic**2, "ci_low": ci.low, "ci_high": ci.high,
                 "p": res.pvalue,
                 "spearman": stats.spearmanr(customers[a_col], customers[b_col]).statistic})
print(pd.DataFrame(rows).round(3).to_string())
Pairrr squared95% interval for rpSpearman
Newsletter opens and repeat orders0.310.100.24 to 0.38below 0.0010.30
Discount depth and order valueminus 0.410.17minus 0.47 to minus 0.34below 0.001minus 0.40
Pages per session and order value0.080.010.00 to 0.160.0450.10
First and second order value0.560.320.51 to 0.61below 0.0010.59

The four values reproduce the statistics chapter's 0.31, minus 0.42, 0.08 and 0.56 to within 0.01. The interval for rr is the column most reports leave out, and it is the most useful one: "between 0.24 and 0.38" tells you the opens and reorders link is real but modest, whatever the sample.

Example: the 0.08 that is "significant", and one keen customer

Look at the third row. A correlation of 0.08 explains under 1% of the variation in order value, and yet its p value is 0.045, below the magic 0.05. With 640 customers, almost any non zero correlation becomes "significant". Significance tells you the correlation is probably not exactly zero. It does not tell you it matters. That is why I read the interval and r2r^2 before the p value, every time.

Now the statistics chapter's warning about whales. Add one customer with 30 opens and six repeat orders:

one_whale = pd.DataFrame({"opens": [30], "repeat_orders": [6]})
with_whale = pd.concat([customers[["opens", "repeat_orders"]], one_whale], ignore_index=True)

print(round(customers["opens"].corr(customers["repeat_orders"]), 3))    # 0.309
print(round(with_whale["opens"].corr(with_whale["repeat_orders"]), 3))  # 0.339
print(round(with_whale["opens"].corr(with_whale["repeat_orders"],
                                     method="spearman"), 3))            # 0.306

One customer in 641 moves Pearson's rr from 0.31 to 0.34. Spearman's barely notices (0.303 without, 0.306 with). When Pearson and Spearman disagree by more than about 0.1, look for the handful of rows doing the work before you quote either. A scatter plot finds them in seconds, which is the subject of showing relationships with scatter plots.

None of this turns a correlation into a cause. Keen customers open emails and reorder because they like hampers, and the email may cause little of either. The way to find out is a holdout test, and for observational data the methods in causal inference in marketing go further than correlation can.

Python traps, in one table

TrapWhat happensThe fix
np.std(x) on a SeriesPopulation standard deviation, ddof=0x.std(ddof=1), written out
stats.skew(x)Unadjusted skew, lower on small samplesstats.skew(x, bias=False) or x.skew()
stats.zscore(x)Divides by the population standard deviationPass ddof=1 or compute it yourself
np.percentile or quantileNine definitions, answers differ on small groupsName the method or interpolation
stats.ttest_ind(a, b)Assumes equal variancesequal_var=False (Welch)
binomtest(...).proportion_ci()Exact (Clopper Pearson) by defaultmethod="wilson" if you want Wilson
x.mode()Returns a Series, meaningless on unrounded money.round(0).mode().iloc[0] or leave it out
Refund rows in the exportInflate the count, drag the mean downSeparate table, net by order_id
UTC timestampsOrders near midnight land in the wrong monthtz_convert to shop time before filtering
Series.mad() from older tutorialsRemoved in pandas 2.0(x - x.mean()).abs().mean()

The last row is a small one. McKinney's 3rd edition still lists mad, the mean absolute deviation, among the descriptive methods6. pandas deprecated it and removed it in version 2.027, so code copied from older tutorials fails. The one line replacement in the table does the same job.

For the person who commissions this

If you are a founder or a marketing lead, you will never run these blocks. You can still check the work in ten minutes with these questions:

  1. Which standard deviation did you use, and which percentile method? (Any answer is fine. "I don't know" is not.)
  2. Show me the cleaning ledger. How many rows were removed, and how did the mean move at each step?
  3. When you say "average basket", is that the mean or the median, and how far apart are they?
  4. For each group you compare, how many orders, and what is the interval around each mean? Is it a t interval or a bootstrap interval?
  5. Was the t test Welch's or Student's?
  6. For this proportion, which interval did you use, and does it ever go below zero?
  7. Is the function that builds the first table in version control, with a test?

Those seven questions separate analysis you can bet budget on from analysis that only looks careful.

My view

My view: descriptive statistics are where most marketing analysis goes wrong, and Python makes it easier to go wrong faster, not harder. The libraries are excellent. Their defaults are reasonable. But they are different defaults, chosen by different people for different fields, and a marketing report that mixes NumPy, pandas and SciPy without naming them will quietly contradict itself.

So I would rather see a plain report with every method named than a clever model built on unnamed ones. One tested function for the first table, one cleaning ledger, Welch's test, Wilson's interval, a bootstrap interval for small skewed groups, and the median next to every mean. None of it is advanced. All of it is the difference between a number that survives a sceptical finance director and one that does not.

Data storytelling, analytics dashboards and Data Science are a core part of my work for clients, and this chapter is the first table I build on any shop's orders. If you want it built on yours, the free workshop is where we agree which decision the numbers should change. You own the code, the accounts and the data, and my prices are published on the transparent pricing page.

Where this fits in the programme

This is the first chapter of Marketing analytics in Python, the companion to my Marketing Analytics series. It leans on the foundations series: loading business data into pandas for getting the export in, cleaning data in pandas for the ledger steps, and statistical models in Python for what comes after description. The next Marketing Analytics chapter, on consumer behaviour, moves from the numbers to the people behind them. The next chapter here, on price elasticity with regression, takes the log of order value seriously.

Conclusion

Every statistic in the statistics chapter takes one or two lines of Python: mean, median, mode, std, skew, quantile, sem, stats.t, binomtest, ttest_ind, pearsonr. Writing them is the easy part. The work is in three habits around them. Clean the export first and keep a ledger, because refunds and time zones move the mean before any statistic does. Name every default, because NumPy, pandas and SciPy disagree on the standard deviation, the skew, the percentile, the z score, the t test and the proportion interval. And put the count, the median and an interval next to every mean, ideally from one tested function, so the first table of every report is the same table. Do that, and Priya's "£102" becomes "£102 from 1,000 orders, median £68, interval £92 to £112, a fifth of it from 20 corporate orders", which is a number she can plan a budget around.

If your reports quote an average basket and nobody can say which standard deviation or which interval sits behind it, bring your order export to my free workshop. We agree the decision it should change, and the first two weeks of work are on me: the cleaning ledger and the first table from this chapter, built and tested on your own data.

Sources

  1. 1.

    Python Software Foundation, pandas release history, Python Package Index (PyPI), accessed January 2026, https://pypi.org/project/pandas/#history

  2. 2.

    pandas development team, PDEP 7: Consistent copy/view semantics in pandas with Copy on Write, and PDEP 14: Dedicated string data type for pandas 3.0, pandas enhancement proposals, 2021 and 2024, https://pandas.pydata.org/pdeps/0007-copy-on-write.html and https://pandas.pydata.org/pdeps/0014-string-dtype.html

  3. 3.

    NumPy developers, Random Generator, NumPy 2.4 documentation, 2025, https://numpy.org/doc/2.4/reference/random/generator.html

  4. 4.

    pandas development team, pandas.Series.std, pandas 2.3 documentation, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.Series.std.html

  5. 5.

    NumPy developers, numpy.std, NumPy 2.4 documentation, 2025, https://numpy.org/doc/2.4/reference/generated/numpy.std.html

  6. 6.

    Wes McKinney, Python for Data Analysis, 3rd edition, O'Reilly, 2022, chapter 4 (NumPy basics, table of array statistical methods) and chapter 5 (Getting started with pandas, section 5.3 Summarizing and computing descriptive statistics), open access edition, https://wesmckinney.com/book/numpy-basics and https://wesmckinney.com/book/pandas-basics

  7. 7.

    Python Software Foundation, statistics: Mathematical statistics functions, Python 3.14 documentation, 2025, https://docs.python.org/3.14/library/statistics.html

  8. 8.

    pandas development team, pandas.Series.skew, pandas 2.3 documentation, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.Series.skew.html

  9. 9.

    SciPy developers, scipy.stats.skew, SciPy 1.16 documentation, 2025, https://docs.scipy.org/doc/scipy-1.16.2/reference/generated/scipy.stats.skew.html

  10. 10.

    D. N. Joanes and C. A. Gill, Comparing measures of sample skewness and kurtosis, Journal of the Royal Statistical Society Series D (The Statistician), volume 47, issue 1, pages 183 to 189, 1998, https://doi.org/10.1111/1467-9884.00122

  11. 11.

    Rob J. Hyndman and Yanan Fan, Sample quantiles in statistical packages, The American Statistician, volume 50, issue 4, pages 361 to 365, 1996, https://doi.org/10.1080/00031305.1996.10473566

  12. 12.

    NumPy developers, numpy.percentile, NumPy 2.4 documentation, 2025, https://numpy.org/doc/2.4/reference/generated/numpy.percentile.html

  13. 13.

    pandas development team, pandas.Series.quantile, pandas 2.3 documentation, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.Series.quantile.html

  14. 14.

    Barbara Illowsky, Susan Dean and others, Introductory Statistics 2e, section 2.6 Skewness and the Mean, Median, and Mode, OpenStax, 2023, https://openstax.org/books/introductory-statistics-2e/pages/2-6-skewness-and-the-mean-median-and-mode

  15. 15.

    SciPy developers, scipy.stats.zscore, SciPy 1.16 documentation, 2025, https://docs.scipy.org/doc/scipy-1.16.2/reference/generated/scipy.stats.zscore.html

  16. 16.

    Barbara Illowsky, Susan Dean and others, Introductory Statistics 2e, section 7.1 The Central Limit Theorem for Sample Means (Averages), OpenStax, 2023, https://openstax.org/books/introductory-statistics-2e/pages/7-1-the-central-limit-theorem-for-sample-means-averages

  17. 17.

    Barbara Illowsky, Susan Dean and others, Introductory Statistics 2e, section 8.2 A Single Population Mean using the Student t Distribution, OpenStax, 2023, https://openstax.org/books/introductory-statistics-2e/pages/8-2-a-single-population-mean-using-the-student-t-distribution

  18. 18.

    SciPy developers, scipy.stats.bootstrap, SciPy 1.16 documentation, 2025, https://docs.scipy.org/doc/scipy-1.16.2/reference/generated/scipy.stats.bootstrap.html

  19. 19.

    Lawrence D. Brown, T. Tony Cai and Anirban DasGupta, Interval Estimation for a Binomial Proportion, Statistical Science, volume 16, issue 2, pages 101 to 133, 2001, https://doi.org/10.1214/ss/1009213286

  20. 20.

    Edwin B. Wilson, Probable Inference, the Law of Succession, and Statistical Inference, Journal of the American Statistical Association, volume 22, issue 158, pages 209 to 212, 1927, https://doi.org/10.1080/01621459.1927.10502953

  21. 21.

    SciPy developers, BinomTestResult.proportion_ci, SciPy 1.16 documentation, 2025, https://docs.scipy.org/doc/scipy-1.16.2/reference/generated/scipy.stats._result_classes.BinomTestResult.proportion_ci.html

  22. 22.

    SciPy developers, scipy.stats.ttest_ind, SciPy 1.16 documentation, 2025, https://docs.scipy.org/doc/scipy-1.16.2/reference/generated/scipy.stats.ttest_ind.html

  23. 23.

    B. L. Welch, The generalization of "Student's" problem when several different population variances are involved, Biometrika, volume 34, issue 1 and 2, pages 28 to 35, 1947, https://doi.org/10.1093/biomet/34.1-2.28

  24. 24.

    Marie Delacre, Daniël Lakens and Christophe Leys, Why Psychologists Should by Default Use Welch's t test Instead of Student's t test, International Review of Social Psychology, volume 30, issue 1, pages 92 to 101, 2017, https://doi.org/10.5334/irsp.82

  25. 25.

    Ronald L. Wasserstein and Nicole A. Lazar, The ASA Statement on p Values: Context, Process, and Purpose, The American Statistician, volume 70, issue 2, pages 129 to 133, 2016, https://doi.org/10.1080/00031305.2016.1154108

  26. 26.

    SciPy developers, scipy.stats.pearsonr, SciPy 1.16 documentation, 2025, https://docs.scipy.org/doc/scipy-1.16.2/reference/generated/scipy.stats.pearsonr.html

  27. 27.

    pandas development team, What's new in 2.0.0 (removal of prior version deprecations), pandas 2.3 documentation, 2023, https://pandas.pydata.org/pandas-docs/version/2.3/whatsnew/v2.0.0.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter