Module 2 · Beginner · Describing data

Z-scores and standardisation

Z-scores measure how unusual a value is in standard deviations. Compare marks from different exams, standardise columns, flag outliers and see StandardScaler.

By theprogrammers team · · 10 min read

Meera scored 78 in maths and 85 in English. Which was the better performance? The raw marks say English. But the maths paper was hard (the class averaged 65) and the English paper was easy (the class averaged 80). What you really want to know is: how far above the class was she, compared with how spread out the class was? That's what a z-score measures.

A z-score turns any value into "how many standard deviations above or below the mean is this?" Once values are in standard deviations, marks, weights and rupees can all be compared on the same scale. Doing it to a whole column is called standardisation, and it's one of the most common steps in machine learning: scikit-learn's StandardScaler does nothing else.

What you need first: range, variance and standard deviation and skewness and kurtosis.

Key terms

  • Z-score (or standard score): how many standard deviations a value is from the mean. Positive above the mean, negative below.
  • Standardise: convert every value in a column to its z-score, giving a column with mean 0 and standard deviation 1.
  • Unit-free: having no units. Z-scores are unit-free, so different measurements can be compared.
  • StandardScaler: scikit-learn's tool for standardising features.

Which mark was more impressive?

Here are the class results for each paper:

PaperMeera's markClass meanClass SD
Maths78658
English85803

In maths, Meera was 13 marks above the mean. In English, only 5. But in English the class was tightly bunched: an SD of 3 means most students scored within a few marks of 80. Being 5 marks above that is unusual. In maths, with an SD of 8, being 13 above is good but less rare.

Measure each gap in standard deviations:

  • Maths: 13 ÷ 8 = 1.63 SDs above the mean.
  • English: 5 ÷ 3 = 1.67 SDs above the mean.

So, measured against her class, the English result was slightly more impressive, even though it was 8 marks closer to the average. Those two numbers are z-scores.

The formula, as a summary of what you just did:

z = (x − mean) ÷ SD

Read it as "subtract the mean, then divide by the standard deviation". Subtracting the mean says how far above or below average the value is; dividing by the SD turns that distance into a number of typical steps.

def z_score(value, mean, sd):
    return (value - mean) / sd

print(round(z_score(78, 65, 8), 2), round(z_score(85, 80, 3), 2))
print(round(z_score(52, 65, 8), 2))
1.62 1.67
-1.62

A mark of 52 in maths gives a z-score of −1.62: the same distance below the mean as 78 is above it. (Python shows 1.625 as 1.62 because, when a number is exactly halfway, round picks the even last digit.)

Notice what happened to the units. Marks minus marks gives marks, and marks divided by marks gives a plain number. Z-scores are unit-free, which is exactly why they let you compare things measured differently.

Standardising a whole column

Apply the same calculation to every value in a column and you've standardised it. Here are real penguin body masses:

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 numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

penguins = sns.load_dataset("penguins").dropna(subset=["body_mass_g", "bill_length_mm"])
mass = penguins["body_mass_g"]
mass_z = (mass - mass.mean()) / mass.std()

print(mass.head(3).to_list())
print(mass_z.head(3).round(2).to_list())
print("mean:", round(mass_z.mean(), 2), " SD:", round(mass_z.std(), 2))
[3750.0, 3800.0, 3250.0]
[-0.56, -0.5, -1.19]
mean: 0.0  SD: 1.0

After standardising, the column has a mean of 0 and an SD of 1, always. (The mean may print as -0.0, a tiny rounding leftover.) The first penguin weighs 3,750 g, about half an SD below the average penguin.

Here's something people often get wrong. Predict: does standardising change the shape of the histogram?

fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))
axes[0].hist(mass, bins=25, color="#d9a05a", edgecolor="white")
axes[0].set_xlabel("Body mass (g)")
axes[0].set_title("Before: grams")
axes[1].hist(mass_z, bins=25, color="#c2410c", edgecolor="white")
axes[1].set_xlabel("Body mass (z-score)")
axes[1].set_title("After: standard deviations from the mean")
plt.tight_layout()
plt.show()
Two histograms of the same penguin body masses. The left one is in grams, from about 2,700 to 6,300, with a main hump around 3,500 g and a long, lumpy right side. The right one is in z-scores, from about −1.9 to 2.6, and has exactly the same shape; only the numbers on the horizontal axis have changed.

The two histograms are identical; only the axis labels changed. Standardising shifts the data (subtracting the mean moves the centre to 0) and rescales it (dividing by the SD sets the spread to 1). It doesn't bend it. Skewed data stays skewed, and two humps stay two humps. In particular, standardising does not make data normal, a mistake you'll see in many tutorials.

Comparing different measurements

Because z-scores are unit-free, you can compare a penguin's bill length (in millimetres) with its weight (in grams). Take the first penguin:

bill = penguins["bill_length_mm"]
bill_z = (bill - bill.mean()) / bill.std()
first = penguins.index[0]
print(f"bill {bill[first]} mm -> z = {bill_z[first]:.2f}")
print(f"mass {mass[first]} g -> z = {mass_z[first]:.2f}")
bill 39.1 mm -> z = -0.88
mass 3750.0 g -> z = -0.56

In millimetres and grams the two numbers can't be compared. In z-scores you can say: this penguin's bill is shorter than average by almost a full SD (−0.88), while its weight is only about half an SD below average (−0.56). Relative to other penguins, its short bill stands out more than its weight.

Z-scores for spotting outliers

A value with a z-score beyond ±3 is more than 3 standard deviations from the mean. In roughly bell-shaped data, that's rare, so |z| > 3 is a common outlier flag.

print("penguins beyond 3 SD:", (mass_z.abs() > 3).sum())
penguins beyond 3 SD: 0

No penguin is that unusual. The rule has a weakness, though. The z-score uses the mean and SD, and an extreme value inflates the SD, which shrinks its own z-score. Here are the 20 delivery times from percentiles, quartiles and the IQR, with a lost rider at 58 minutes:

times = pd.Series([18, 22, 25, 19, 31, 27, 24, 21, 35, 26, 23, 29, 20, 24, 58, 22, 28, 25, 30, 26])
times_z = (times - times.mean()) / times.std()
print(round(times_z.max(), 2))
3.68

The 58-minute delivery is more than twice the typical time, yet its z-score is 3.68, not far past the cut-off. Measured against the other 19 deliveries alone (mean 25.0, SD 4.4), it would be about 7.6 SDs out. In a small sample, one outlier drags the mean and SD towards itself and partly hides itself. That's why, for small or skewed data, the 1.5 × IQR rule is often the safer flag.

Where machine learning uses z-scores

StandardScaler standardises every feature: it subtracts each column's mean and divides by its SD. Check that it's the same calculation:

from sklearn.preprocessing import StandardScaler

scaled = StandardScaler().fit_transform(penguins[["body_mass_g"]])
manual = (mass - mass.mean()) / mass.std(ddof=0)
print(np.allclose(scaled.ravel(), manual))
True

ddof=0 matters: StandardScaler divides by n, like NumPy, while pandas' .std() divides by n − 1 (see range, variance and standard deviation). .ravel() flattens the scaler's one-column matrix into a plain list of numbers.

Why do models need this? Distance-based models such as KNN add up differences across features, so without standardising, a feature measured in grams (differences in the hundreds) would swamp one in millimetres (differences of a few). Gradient descent also trains faster when features are on similar scales. Feature scaling covers this in detail.

One rule matters more than any other: work out the mean and SD from the training data only, then use those same numbers on the test data. If the test data's mean leaks into the scaling, the model gets a sneak preview of data it's supposed to be meeting for the first time.

Common mistakes

  • Thinking standardising makes data normal. It only shifts and rescales; the shape stays the same.
  • Mixing up ddof. Pandas' .std() and StandardScaler give slightly different z-scores on small data.
  • Trusting |z| > 3 on small or skewed samples. Outliers inflate the SD and hide themselves. Use the IQR rule too.
  • Fitting the scaler on all the data. Fit it on the training set only, and reuse it for the test set.

Practice

  1. A student scored 64 in a test with mean 70 and SD 4. What's their z-score, and what does it mean?
Show the answer

z = (64 − 70) ÷ 4 = −1.5. They scored one and a half standard deviations below the class average.

  1. Rohan's z-score in physics is 2.0. The class mean was 58 and the SD 9. What was his mark?
Show the answer

Undo the formula: mark = mean + z × SD = 58 + 2 × 9 = 76.

  1. Predict, then check: after standardising flipper length, what are the mean and SD? Is the histogram's shape the same as before?
Show the answer

Mean 0 and SD 1, always. The shape doesn't change: it still has two humps.

flipper = penguins["flipper_length_mm"]
flipper_z = (flipper - flipper.mean()) / flipper.std()
print(round(flipper_z.mean(), 2), round(flipper_z.std(), 2))
-0.0 1.0
  1. Two job candidates took different aptitude tests. Asha scored 720 on a test with mean 600 and SD 80; Vikram scored 31 on a test with mean 25 and SD 3. Who did better relative to the people who took their test?
Show the answer

Asha: (720 − 600) ÷ 80 = 1.5. Vikram: (31 − 25) ÷ 3 = 2.0. Vikram did better relative to his group: he was 2 SDs above his test's mean, against Asha's 1.5.

  1. Explain in your own words why the 58-minute delivery's z-score was smaller than you might expect.
Show the answer

The z-score divides by the SD, and the 58 itself makes the SD much bigger (it's a huge squared deviation). A bigger SD means each SD is a longer step, so 58 is fewer steps from the mean. The outlier partly hides itself.

Interview questions

What is a z-score, and when would you use it?

A z-score is (x − mean) / SD: the number of standard deviations a value lies from the mean. It's used to compare values from different scales or distributions, to standardise features for models, and to flag potential outliers (for example |z| > 3), keeping in mind that it assumes a meaningful mean and SD.

What's the difference between standardisation and normalisation?

Standardisation rescales a feature to mean 0 and standard deviation 1 (z-scores), with no fixed range. Min-max normalisation rescales it to a fixed range, usually 0 to 1. Neither changes the shape of the distribution. Standardisation is less affected by a single extreme value than min-max scaling, whose range is set entirely by the minimum and maximum.

Key takeaways

  • A z-score says how many standard deviations a value is from the mean: z = (x − mean) ÷ SD.
  • Z-scores are unit-free, so they compare marks from different exams or features in different units.
  • Standardising a column gives mean 0 and SD 1 but doesn't change its shape, and doesn't make it normal.
  • |z| > 3 is a common outlier flag, but outliers inflate the SD and can hide themselves; check with the IQR too.
  • StandardScaler is standardisation with ddof=0; fit it on training data only.

Frequently asked questions

Can a z-score be bigger than 3?

Yes. Nothing limits it. In bell-shaped data, values beyond 3 SDs are rare (about 3 in 1,000), but in heavy-tailed data they're much more common, as skewness and kurtosis showed.

What does a z-score of 0 mean?

The value equals the mean exactly.

Do I need to standardise for tree-based models?

No. Decision trees, random forests and gradient boosting split on thresholds, and shifting or rescaling a feature doesn't change which rows fall on each side. Standardising matters for linear models, KNN, SVMs, PCA and neural networks.

What to learn next

  1. Put every descriptive tool together on real data in summary statistics in pandas.
  2. See standardising inside a model pipeline in feature scaling.
  3. Watch distances change with scaling in K-nearest neighbours explained.