Z-Scores — Standardization and the Normal Table
Descriptive Statistics
Unlock the Power of Standardization
Z-scores transform any dataset into a universal language — making it possible to compare values from completely different scales, detect outliers, and unlock probabilities from the normal table.
Key things this concept helps with:
- Cross-Scale Comparison — Compare a math test score to an essay rubric rating fairly
- Outlier Detection — Identify values that fall unusually far from the mean
- Probability Calculation — Convert any normal distribution into the standard normal for easy probability lookup
- Machine Learning Pipelines — Standardize features so algorithms treat them equally
Once you master z-scores, every normal distribution becomes as familiar as the standard normal table.
What You'll Learn
- 1Compute and interpret a z-score for any value in a distribution
- 2Move in both directions between raw scores, z-scores and percentiles
- 3Read cumulative probabilities and tail areas from the standard normal table
- 4Choose between z-score, min-max and robust scaling in a modelling pipeline
What is a Z-Score?
Definition
A z-score (standard score) indicates how many standard deviations an element is from the mean. It standardizes values for cross-scale comparison.
The z-score answers a single question: how unusual is this value relative to its own population? The numerator measures distance from the centre, the denominator converts that distance into standard-deviation units, and the sign records which side of the mean you are on. Two properties follow immediately and make the transform useful everywhere: for any dataset, the z-scores have mean 0 and standard deviation 1, and the transformation is linear, so it never changes the shape of the distribution or the ranking of the observations.
import numpy as np
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
scores = np.array([72, 85, 91, 68, 77, 94, 83, 79, 88, 62])
mean, std = scores.mean(), scores.std(ddof=1)
z = (scores - mean) / std
print(f"Mean={mean:.2f}, Std={std:.2f}\n")
for s, zz in zip(scores, z):
print(f" Score={s:3d} z={zz:+.3f} ({abs(zz):.1f}σ {'above' if zz>0 else 'below'} mean)")
Population versus sample denominators
The formula is written with and , which assumes you know the population parameters. When you estimate them from the sample you must be explicit about which denominator you used: dividing by the sample standard deviation with gives a standardized score for a sample, while dividing by the biased version reproduces exactly what sklearn's StandardScaler does. As soon as inference enters the picture and is unknown, the correct reference distribution is the Student with degrees of freedom, not the standard normal.
Comparing Across Different Tests
alice_math = 85; mu_m = 75; sd_m = 10 # Math test
alice_essay = 4.5; mu_e = 4.0; sd_e = 0.5 # Essay rubric (0-6)
z_math = (alice_math - mu_m) / sd_m
z_essay = (alice_essay - mu_e) / sd_e
print(f"Math z-score: {z_math:.2f}")
print(f"Essay z-score: {z_essay:.2f}")
print(f"Better performance: {'Math' if z_math > z_essay else 'Essay'}")
Direction matters whenever lower raw values are better. For a completion-time benchmark of minutes with , a runner finishing in 34 minutes earns , which is one standard deviation better than average, not worse. Comparing across measures therefore requires aligning the sign first: flip the sign for time, error rate, or any other lower-is-better metric before you rank one z-score against another.
Z-Scores and Normal Probabilities
Once a value sits on the standard normal scale, probabilities come from one table instead of one table per distribution. The most useful reference points are worth memorizing, because they reappear in confidence intervals, control limits, and hypothesis tests.
| z | Cumulative percentile | Area in the tails |
|---|---|---|
| −2.326 | 1st | 2% beyond |
| −1.645 | 5th | 10% beyond |
| −1.282 | 10th | 20% beyond |
| 0 | 50th | 50% on each side |
| 1.282 | 90th | 20% beyond |
| 1.645 | 95th | 10% beyond |
| 1.960 | 97.5th | 5% beyond |
| 2.326 | 99th | 2% beyond |
| 3.000 | 99.865th | 0.27% beyond |
print("Key z-score probabilities:")
print(f"P(Z < 1.645) = {norm.cdf(1.645):.4f} (90th pct)")
print(f"P(Z < 1.960) = {norm.cdf(1.960):.4f} (97.5th pct)")
print(f"P(Z < 2.326) = {norm.cdf(2.326):.4f} (99th pct)")
print(f"P(-1.96<Z<1.96) = {norm.cdf(1.96)-norm.cdf(-1.96):.4f} (95%)")
# Given probability -> find z
print(f"\nZ for 90th percentile: {norm.ppf(0.90):.4f}")
print(f"Z for 97.5th: {norm.ppf(0.975):.4f}")
print(f"Z for 99th: {norm.ppf(0.99):.4f}")
# Reverse direction: raw score at the 90th percentile
mu, sigma = 520, 80
x = mu + norm.ppf(0.90) * sigma
print(f"90th percentile of N({mu}, {sigma}): {x:.1f}")
Assumptions Behind the Normal Table
The z-score formula itself assumes nothing about shape: any distribution with a defined mean and standard deviation can be standardized, and the ranking of points never changes. What does require an assumption is turning that z-score into a probability. Quoting "the 97.5th percentile" from the standard normal table presumes the underlying data is normal, or that you are averaging over a large enough sample for the central limit theorem to apply.
When normality is doubtful, Chebyshev's inequality gives a guarantee that holds for any distribution with a finite variance: at least of observations lie within standard deviations of the mean. That is at least 75% within two standard deviations and at least 88.9% within three, which is a far weaker statement than the 95.4% and 99.7% the normal curve promises, and it is the honest bound to quote for skewed or heavy-tailed data.
Z-Scores Versus Other Scaling Methods
Standardization is one of several transformations, and the choice changes model behaviour. Distance-based algorithms care about scale directly, while tree ensembles barely notice it.
| Method | Formula | Centre / scale | Outlier sensitivity | Typical use |
|---|---|---|---|---|
Z-score (StandardScaler) | (x − mean) / sd | Mean, standard deviation | High | Roughly symmetric features |
Min-max (MinMaxScaler) | (x − min) / (max − min) | Minimum, range | High | Bounded inputs, images, neural nets |
Robust (RobustScaler) | (x − median) / IQR | Median, IQR | Low | Skewed or contaminated features |
Max-abs (MaxAbsScaler) | x / max(abs(x)) | Zero, maximum magnitude | Moderate | Sparse matrices, TF-IDF |
X = np.array([
[170, 70, 25],
[180, 85, 30],
[160, 55, 22],
[175, 80, 35],
[165, 60, 28],
], dtype=float)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
print("Standardized features (z-scores):")
print(X_scaled.round(3))
print(f"Column means (should be ~0): {X_scaled.mean(axis=0).round(6)}")
print(f"Column stds (should be ~1): {X_scaled.std(axis=0).round(4)}")
A practical warning belongs with that table: fit the scaler on the training fold only, then apply the same parameters to validation and test data. Calling fit_transform on the whole dataset leaks information about the test distribution into the training pipeline, and the resulting scores no longer represent what the model will see in production.
Z-Scores in Machine Learning
| ML Application | Z-Score Usage | Why |
|---|---|---|
| StandardScaler | z = (x − μ) / σ | Neural networks need normalized input |
| Anomaly detection | |z| beyond 3 → outlier | Production monitoring |
| Feature normalization | Compare features on same scale | Distance-based algorithms |
| Batch normalization | Normalize layer activations | Stabilizes deep learning |
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import LocalOutlierFactor
np.random.seed(42)
# Z-score based anomaly detection
data = np.random.randn(100, 3)
z_scores = np.abs((data - data.mean(axis=0)) / data.std(axis=0))
anomalies = (z_scores > 3).any(axis=1)
print(f"Data points with any |z| > 3: {anomalies.sum()}")
# StandardScaler = z-score normalization
scaler = StandardScaler()
scaled = scaler.fit_transform(data)
print(f"\nOriginal: mean={data.mean():.4f}, std={data.std():.4f}")
print(f"Scaled: mean={scaled.mean():.4f}, std={scaled.std():.4f}")
Why the z-rule misses anomalies in contaminated data
The mean and the standard deviation are themselves statistics with a 0% breakdown point, so a single extreme value inflates them. Once the denominator grows, the z-scores of every other point shrink, and a moderate anomaly can slip under the threshold. Consider a batch of 1,000 readings at 0, one at 10,000 and one at 12: the standard deviation explodes to about 316, the reading of 12 earns a z-score near 0.01, and the rule declares it ordinary. The 1.5×IQR rule, whose centre and scale are quartiles, does not suffer the same masking.
import numpy as np
readings = np.concatenate([np.zeros(1000), [12.0, 10000.0]])
z = np.abs((readings - readings.mean()) / readings.std())
print(f"z of the mild anomaly (12): {z[-2]:.4f} -> flagged: {z[-2] > 3}")
print(f"z of the extreme value: {z[-1]:.2f} -> flagged: {z[-1] > 3}")
q1, q3 = np.percentile(readings, [25, 75])
iqr = q3 - q1
print(f"IQR={iqr}, fences=[{q1 - 1.5*iqr}, {q3 + 1.5*iqr}] -> both points flagged")
⚠️Standardization is not normalization of shape
Frequently Asked Questions
Does a z-score require the data to be normally distributed?
No. The formula needs only a mean and a standard deviation, and it works on any distribution. Normality enters only when you convert the z-score into a percentile or a tail probability using the standard normal table.
What does a z-score of exactly zero mean?
It marks the mean itself, since the numerator vanishes. Half the observations need not sit below it — the median and the mean coincide only for symmetric distributions.
Why do confidence intervals use 1.96 instead of 2?
1.96 is the standard normal value that leaves 2.5% in each tail, giving exactly 95% in the middle. Using 2 would capture 95.45%, a small difference that shows up immediately in sample size calculations.
Can you compare z-scores from two different samples?
Yes, that is the point of standardization: each score is expressed relative to its own mean and spread. Keep the direction of the metric aligned, and remember that a z-score of 1 in a small sample is far less certain than one in a large sample.
Common Mistakes
Comparing raw scores from tests with different spreads
Fix: Convert both to z-scores against their own mean and standard deviation before comparing, and align the direction of any lower-is-better metric.
Using the standard normal table for strongly skewed data
Fix: Check normality first, or quote a distribution-free bound such as Chebyshev's instead of a normal percentile.
Fitting StandardScaler on the full dataset before splitting
Fix: Fit on the training fold only and reuse those parameters for validation and test data to avoid leakage.
Key Takeaways
- z = (x − μ)/σ measures distance from the mean in standard deviation units, and the resulting scores always have mean 0 and standard deviation 1
- Because the transform is linear it never changes ranks or shape — only the units, which is why cross-scale comparison becomes valid
- Percentiles and tail areas come from the standard normal: 1.645 for 95%, 1.96 for 97.5%, and 3 for 99.865%
- Normality is required for probabilities, not for the formula itself; Chebyshev supplies a distribution-free fallback of at least 75% within two standard deviations
- The z-based outlier rule has a 0% breakdown point, so contaminated data needs quartile-based fences instead
Interview Questions
Q1: Walk me through what a z-score of −2.33 means.
The value sits 2.33 standard deviations below the mean, which under normality corresponds to roughly the 1st percentile — about one observation in a hundred falls at or below it.
Q2: How do you find the raw score at the 95th percentile of a distribution with mean 100 and standard deviation 15?
The 95th percentile is not 1.96 here — that is the value with 2.5% above it. You want z = 1.645, so x = 100 + 1.645 × 15 = 124.7. For a symmetric interval of 95% in the middle you would use 1.96.
Q3: Why is standardization important for k-nearest neighbours but not for decision trees?
kNN computes Euclidean distances, so a feature measured in thousands dominates one measured in fractions unless both are put on a common scale. Trees split on thresholds within a single feature, so any monotone rescaling leaves every split identical.
Q4: What is the difference between a z-score and a t-score?
The z-score divides by a known population standard deviation and references the standard normal; the t-score divides by an estimated sample standard deviation and references the t distribution, whose tails widen as the degrees of freedom shrink.
Z-scores are the bridge between raw data and the standard normal table — once you standardize, the entire normal distribution is at your fingertips.