Module 2 · Beginner · Describing data

Range, variance and standard deviation explained

Range, variance and standard deviation with two batters who both average 50: deviations, why we square them, n vs n − 1, and pandas vs NumPy defaults.

By theprogrammers team · · 12 min read

Two batters both average 50 runs over their last five innings. A selector who looks only at the average can't tell them apart. But one scored 48, 52, 50, 45 and 55, and the other scored 5, 120, 10, 95 and 20. The first is as steady as a wall; the second either wins the match or is out cheaply. The difference between them is spread: how far the scores wander from the average.

A measure of centre (mean, median or mode) says what's typical. A measure of spread says how much you can trust "typical". Below, you'll build the standard measure, the standard deviation, from the ground up, so you can see why it's defined the way it is, and why NumPy and pandas give slightly different answers for it.

What you need first: mean, median and mode.

Key terms

  • Spread (or dispersion): how much values vary around their centre.
  • Range: the largest value minus the smallest.
  • Deviation: how far one value is from the mean, value − mean. Positive above the mean, negative below.
  • Variance: the average of the squared deviations. Measured in squared units.
  • Standard deviation (SD): the square root of the variance. Roughly, a typical distance from the mean, in the original units.
  • Sample variance: variance worked out with n − 1 instead of n, used when the data is a sample.

Two batters, one average

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

steady = np.array([48, 52, 50, 45, 55])
risky = np.array([5, 120, 10, 95, 20])
print(steady.mean(), risky.mean())
50.0 50.0

Same mean. Here's how differently they're spread:

fig, ax = plt.subplots(figsize=(9, 3.5))
for row, (name, scores, colour) in enumerate([("steady", steady, "#0f766e"), ("risky", risky, "#c2410c")]):
    sd = scores.std()
    ax.axvspan(scores.mean() - sd, scores.mean() + sd, ymin=row / 2 + 0.1, ymax=row / 2 + 0.4, color=colour, alpha=0.15)
    ax.scatter(scores, [row] * 5, s=110, color=colour, zorder=3)
    ax.text(132, row, f"SD = {sd:.1f}", va="center", fontsize=12)
ax.axvline(50, color="#1c1917", linestyle="--", label="mean: 50 for both")
ax.set_yticks([0, 1], ["steady", "risky"])
ax.set_xlim(-5, 165)
ax.set_ylim(-0.6, 1.6)
ax.set_xlabel("Runs scored")
ax.set_title("Same average, very different spread")
ax.legend(loc="upper left")
plt.show()
Two rows of five dots on a runs axis from 0 to 145, with a dashed line at the shared mean of 50. The steady batter's teal dots are bunched between 45 and 55, inside a narrow shaded band, labelled SD = 3.4. The risky batter's orange dots are scattered from 5 to 120, with a wide shaded band from about 2 to 98, labelled SD = 47.9; the 120 lies outside the band.

The shaded bands show one standard deviation either side of the mean. Most scores sit inside the band, but not all: the risky batter's 120 is outside it. You'll soon see exactly where 3.4 and 47.9 come from.

The range: quick but crude

The simplest measure of spread is the range, the highest value minus the lowest:

print(steady.max() - steady.min(), risky.max() - risky.min())
10 115

The range separates the batters at once. But it only looks at two values, the two most extreme. If the steady batter had one freak innings of 140, their range would jump to 95, even though the other four scores are as steady as ever. A good measure of spread should use every value.

Deviations: how far is each value from the mean?

Start with every score's distance from the mean, called its deviation:

print(steady - steady.mean())
print(risky - risky.mean())
[-2.  2.  0. -5.  5.]
[-45.  70. -40.  45. -30.]

The steady batter's deviations are small; the risky batter's are huge. So why not just average the deviations? Predict the answer before you run this:

print((steady - steady.mean()).sum(), (risky - risky.mean()).sum())
0.0 0.0

Both add up to exactly 0. That's not a coincidence: it's what the mean is. The mean is the balance point, so the deviations above it exactly cancel the deviations below it, for every dataset. An average deviation is always 0, which is useless. The signs have to go.

Squaring the deviations: the variance

There are two ways to get rid of the signs: take the absolute value (ignore the minus sign) or square each deviation. Statistics usually squares them. The variance is the average of the squared deviations:

squared = (risky - risky.mean()) ** 2
print(squared)
print("variance:", squared.mean())
[2025. 4900. 1600. 2025.  900.]
variance: 2290.0

For the risky batter, the squared deviations add up to 11,450, and their average is 2,290. For the steady batter, the same steps give (4 + 4 + 0 + 25 + 25) ÷ 5 = 11.6.

The formula, as a summary of those steps, for n values with mean x̄:

variance = Σ(x − x̄)² ÷ n

Read it as "for each value, subtract the mean and square the result; add those up; divide by how many values there are".

Why square instead of using absolute values? Two reasons. Squaring punishes big deviations much more than small ones: a deviation of 70 contributes 4,900, while two deviations of 35 contribute only 2,450 between them. So variance is very sensitive to values far from the mean. And squares are much easier to work with in further maths, which is why the same squared distances appear in mean squared error, least squares regression and the normal distribution. The absolute-value version, the mean absolute deviation, exists too, and it's less affected by outliers.

Back to runs: the standard deviation

The variance has an awkward unit. The deviations were in runs, so the squared deviations are in "runs squared", which means nothing to a cricket fan. Taking the square root brings it back to runs. That's the standard deviation:

print("steady SD:", round(float(np.sqrt(steady.var())), 2), "=", round(float(steady.std()), 2))
print("risky SD: ", round(float(np.sqrt(risky.var())), 2), "=", round(float(risky.std()), 2))
steady SD: 3.41 = 3.41
risky SD:  47.85 = 47.85

NumPy's .var() and .std() do the whole calculation; the SD is the square root of the variance. Read the standard deviation as roughly how far a typical value sits from the mean. The steady batter's innings are typically about 3 runs from 50; the risky batter's are typically about 48 runs away. Those two numbers say what the selector needed to know.

n or n − 1? Why pandas and NumPy disagree

Run the same calculation in pandas and you get a different answer. Predict which one is bigger:

print(round(float(np.std(steady)), 2))
print(round(float(pd.Series(steady).std()), 2))
3.41
3.81

NumPy divides by n (here 5) by default. Pandas divides by n − 1 (here 4), so its answer is a bit bigger. Both are right; they answer different questions.

  • **Dividing by *n*** describes the spread of exactly these values. Use it when your data is the whole population, such as all five innings you care about.
  • **Dividing by n − 1 estimates the spread of a population from a sample. This is the sample standard deviation**, and it's the usual choice in statistics.

Why would a sample need a correction? Because the deviations are measured from the sample's own mean, which always sits in the middle of the sample's values. The true population mean is usually a little further away. So deviations from the sample mean come out slightly too small, on average. Dividing by a slightly smaller number makes up for it. You can see this happen. Take thousands of samples of 5 from a population whose true variance is 100, and average the variances each method gives:

rng = np.random.default_rng(0)
samples = rng.normal(loc=50, scale=10, size=(20_000, 5))   # 20,000 samples of 5; true variance 100
print("divide by n:    ", samples.var(axis=1, ddof=0).mean().round(1))
print("divide by n − 1:", samples.var(axis=1, ddof=1).mean().round(1))
divide by n:     80.1
divide by n − 1: 100.1

rng.normal(loc=50, scale=10, ...) draws random values with a true mean of 50 and a true SD of 10 (so a true variance of 100). ddof stands for "delta degrees of freedom": ddof=0 divides by n and ddof=1 by n − 1. With samples of 5, dividing by n comes out about 20% too low on average, and dividing by n − 1 is right on target. With large samples, the difference between the two shrinks to almost nothing.

The practical rule: know which one your tool uses. NumPy defaults to ddof=0, pandas to ddof=1. Pass ddof yourself when it matters.

Spread in real data

Download the data: penguins.csv (15 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("penguins.csv").

import seaborn as sns

penguins = sns.load_dataset("penguins")
print(penguins.groupby("species")["body_mass_g"].agg(["mean", "std"]).round(0))
             mean    std
species                 
Adelie     3701.0  459.0
Chinstrap  3733.0  384.0
Gentoo     5076.0  504.0

Read each row as "a typical penguin of this species is within about one SD of the mean". In data with a single hump, a handy rule of thumb is that about two thirds of the values lie within one SD of the mean, and about 95% within two. Check it for Gentoos:

gentoo = penguins.loc[penguins["species"] == "Gentoo", "body_mass_g"].dropna()
within_1 = (abs(gentoo - gentoo.mean()) <= gentoo.std()).mean()
within_2 = (abs(gentoo - gentoo.mean()) <= 2 * gentoo.std()).mean()
print(f"within 1 SD: {within_1:.0%}, within 2 SD: {within_2:.0%}")
within 1 SD: 67%, within 2 SD: 98%

abs(gentoo - gentoo.mean()) <= gentoo.std() is True for each penguin within one SD of the mean; taking .mean() of True/False values gives the share that are True. You'll see where the two-thirds and 95% come from in the distributions module, with the normal distribution.

Where machine learning uses spread

  • Feature scaling: StandardScaler subtracts each feature's mean and divides by its standard deviation (using n, like NumPy), so every feature ends up with an SD of 1. Without it, a feature measured in rupees, with an SD of thousands, would swamp one measured in years. See feature scaling.
  • Useless features: a column whose variance is almost 0 is nearly constant, so it can't help tell examples apart. Scikit-learn's VarianceThreshold drops such columns.
  • Error sizes: the root mean squared error (RMSE) of a regression model is a standard deviation of its errors: a typical size of a mistake, in the target's own units.
  • Unstable models: if a model's cross-validation scores have a large SD, its performance depends heavily on which data it saw.

Common mistakes

  • Reporting a mean without a spread. "Average 50" means very different things for the two batters. Give the SD (or another spread) alongside.
  • Comparing standard deviations in different units. An SD of 500 g and an SD of 5 mm can't be compared directly. Compare relative spread, such as SD ÷ mean, instead.
  • Mixing up variance and standard deviation. Variance is in squared units; quote the SD when describing data to people.
  • Forgetting that the SD is sensitive to outliers. One extreme value inflates it, just as it drags the mean. For skewed data, the interquartile range, coming up next, is more robust.

Practice

  1. Work out the variance and SD of 2, 4, 6 by hand, dividing by n.
Show the answer

Mean 4. Deviations −2, 0, 2. Squares 4, 0, 4, sum 8. Variance 8 ÷ 3 ≈ 2.67. SD √2.67 ≈ 1.63.

print(round(float(np.var([2, 4, 6])), 2), round(float(np.std([2, 4, 6])), 2))
2.67 1.63
  1. Predict, then check: what are the variance and SD of 7, 7, 7, 7?
Show the answer

Both 0: every value equals the mean, so every deviation is 0. There's no spread at all.

print(np.var([7, 7, 7, 7]), np.std([7, 7, 7, 7]))
0.0 0.0
  1. Add 10 runs to every one of the steady batter's scores. What happens to the mean and to the SD? Why?
Show the answer

The mean goes up by 10, to 60, but the SD stays 3.41. Every score and the mean move together, so every deviation is unchanged.

print((steady + 10).mean(), round(float((steady + 10).std()), 2))
60.0 3.41
  1. Now double every score instead. What happens to the SD and to the variance?
Show the answer

The SD doubles, to 6.82, because every deviation doubles. The variance goes up four times, to 46.4, because it's built from squared deviations: 2² = 4.

  1. A friend computes the SD of 10 exam marks with NumPy, and you compute it with pandas. You get 8.4 and they get 8.0. Who made a mistake?
Show the answer

Nobody. Pandas divides by n − 1 = 9 and NumPy by n = 10, so pandas' answer is bigger: 8.0 × √(10 ÷ 9) ≈ 8.43. If the 10 marks are a sample used to estimate a larger group's spread, the pandas value is the usual choice.

  1. In your own words, explain why the average of the deviations is always 0, and why that forces statisticians to square them (or take absolute values).
Show the answer

The mean is the balance point of the data, so the total distance of the values above it equals the total distance of the values below it; positive and negative deviations cancel exactly. To measure how far values are from the mean in total, the signs have to be removed first, by squaring or by taking absolute values.

Interview questions

What is the difference between variance and standard deviation?

Variance is the average squared deviation from the mean, in squared units. The standard deviation is its square root, in the original units, so it's easier to interpret as a typical distance from the mean. Variance is convenient mathematically, for example variances of independent variables add.

Why do we divide by n − 1 for the sample variance?

Deviations are measured from the sample mean, which is fitted to the sample and so is closer to the data points than the true population mean. This makes the sum of squared deviations too small on average. Dividing by n − 1 (Bessel's correction) makes the sample variance an unbiased estimator of the population variance. One degree of freedom is used up by estimating the mean.

Key takeaways

  • Spread measures how much values vary around the centre; always report it with the centre.
  • The range uses only the two extreme values, so a single outlier changes it a lot.
  • Deviations from the mean always add up to 0, so they're squared: the variance is the average squared deviation.
  • The standard deviation is the square root of the variance: a typical distance from the mean, in the original units.
  • NumPy divides by n (ddof=0) and pandas by n − 1 (ddof=1); use n − 1 to estimate a population's spread from a sample.

Frequently asked questions

Is a large standard deviation bad?

Not in itself. It describes the data; whether it's bad depends on the situation. A large SD in delivery times is bad for customers. A large SD in a feature can be useful to a model, because it means the feature varies enough to tell examples apart.

What's a good standard deviation?

There's no universal value: it depends on the units and the mean. Comparing the SD with the mean helps. The coefficient of variation, SD ÷ mean, gives a unit-free measure of relative spread.

Should I use the standard deviation or the interquartile range?

For roughly symmetric data without big outliers, the SD. For skewed data or data with outliers, the interquartile range, which you'll meet in the percentiles lesson, because it isn't dragged by extreme values.

What to learn next

  1. See how scaling uses the SD in feature scaling.
  2. Revisit centre in mean, median and mode.
  3. Get the fast overview in statistics for machine learning.