Python Mean, Median, Mode and Deviation

Use mean, median, mode and standard deviation to describe ML features, build baselines and standardise inputs without leaking test data.

Lesson 91 of 107Advanced13 min read

Before training any model, you summarise its data: what's typical, how spread out it is and whether anything looks wrong. The four classic summary statistics, mean, median, mode and standard deviation, do that job, and in machine learning they do two more: they provide baselines to beat, and they power standardisation, rescaling features so they're comparable.

Python
from statistics import mean, pstdev
hours = [2, 2, 3, 3, 10]
z_scores = [(h - mean(hours)) / pstdev(hours) for h in hours]
print([round(z, 2) for z in z_scores])   # [-0.66, -0.66, -0.33, -0.33, 1.98]

This lesson focuses on those ML uses. For the general meaning of each statistic, the effect of outliers and how to report results, see statistics with Python. The examples describe delivery durations for a courier company predicting late parcels.

Mean and median

Mean and median are the first things to compute for every numeric feature and target:

Python
from statistics import mean, median
delivery_hours = [2, 2, 3, 3, 10]
print(mean(delivery_hours), median(delivery_hours))   # 4 3

A large gap between them signals skew: here one 10-hour delivery lifts the mean to 4 while the typical delivery takes 3. That affects ML in two ways:

  • Baselines: predicting the mean minimises average squared error; predicting the median minimises average absolute error. Pick the baseline that matches the metric you'll report, because a model should be compared with the strongest simple alternative.
  • Missing values: filling gaps with the mean drags imputed values towards outliers; the median is the usual safer choice for skewed features.

Compute these on the training data only, then apply the same values to validation and test data, as explained in the last section.

Mode

The mode, the most frequent value, matters most for categorical features, such as delivery region, vehicle type or day of week, where mean and median don't exist:

Python
from statistics import multimode
regions = ["north", "south", "north", "east", "south"]
print(multimode(regions))     # ['north', 'south']: a tie

multimode() returns every value tied for most frequent, so ties are visible instead of being broken arbitrarily. In ML, the mode is the standard way to fill missing categorical values and the natural baseline for classification: always predicting the most common class (DummyClassifier(strategy="most_frequent") in scikit-learn).

That baseline is also a warning. If 92% of parcels arrive on time, a classifier that always says "on time" is 92% accurate and completely useless. Knowing the mode and its share of the data tells you what accuracy a model must beat before it's worth anything.

Standard deviation

Standard deviation measures typical distance from the mean, in the feature's own units. In ML it's used to standardise features into z-scores:

z = (value − mean) ÷ standard deviation

After standardisation every feature has mean 0 and standard deviation 1. That matters because many algorithms, including k-nearest neighbours, k-means, regularised regression and neural networks, compare or penalise features numerically. Without scaling, a feature measured in metres would dominate one measured in kilometres purely because its numbers are bigger.

Python
from statistics import mean, pstdev
distance_km = [1.2, 3.5, 0.8, 5.1, 2.4]
mu, sigma = mean(distance_km), pstdev(distance_km)
print([round((d - mu) / sigma, 2) for d in distance_km])

scikit-learn's StandardScaler uses the population standard deviation (dividing by n), as pstdev() does. Tree-based models such as decision trees and random forests don't need scaling, because they split on thresholds rather than distances.

Model features

Summary statistics are learned from data, so in ML they're part of the model and must follow the same rules as the model:

Python
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

X_train, X_test = train_test_split(X, test_size=0.25, random_state=0)
scaler = StandardScaler().fit(X_train)      # learn mean and sd from training rows only
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)    # reuse the training statistics

Computing the mean and standard deviation on the whole dataset before splitting lets information about the test rows leak into training, which makes test scores slightly optimistic. Putting the scaler inside a Pipeline with the model guarantees it's refitted correctly inside every cross-validation fold.

Summaries also compress: two features with the same mean and standard deviation can have very different shapes, such as one cluster versus two. Look at percentiles and a histogram too, as in data distribution and percentiles.

Independent practice and a worked check

Task: describe delivery durations with all four summaries and explain how one long delay changes their interpretation.

Python
from statistics import mean, median, multimode, pstdev

normal = [2, 3, 3, 4, 3]
with_delay = normal + [15]

for label, hours in [("normal week", normal), ("with one delay", with_delay)]:
    print(f"{label:<15} mean {mean(hours):.2f}  median {median(hours)}  "
          f"mode {multimode(hours)}  sd {pstdev(hours):.2f}")
Text
normal week     mean 3.00  median 3  mode [3]  sd 0.63
with one delay  mean 5.00  median 3.0  mode [3]  sd 4.51

One 15-hour delay moves the mean from 3 to 5 and multiplies the standard deviation sevenfold, while the median and mode stay at 3. A scaler fitted on the second week would compress all normal deliveries into a narrow band of z-scores. For the worked check, multimode helps represent ties among most frequent values.

Reference and next practice

scikit-learn's preprocessing guide explains scaling, and its common pitfalls page covers leakage. Continue with data distribution and percentiles and linear regression. Practise with the Python exercises and Python quiz.

Mean, Median, Mode and Deviation Summary

  • Mean and median: The mean adds every observation while the median follows ordered position.
  • Mode: A mode is a most frequent observed value, and multiple values can tie.
  • Standard deviation: Standard deviation expresses spread in the original measurement units.
  • Model features: Summary statistics can describe inputs and support simple baselines.

Mean, Median, Mode and Deviation Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Mean, Median, Mode and Deviation in a small program

Python
from statistics import mean, median, multimode, pstdev
hours = [2, 2, 3, 3, 10]
print(mean(hours))
print(median(hours))
print(multimode(hours))
print(round(pstdev(hours), 2))
Output
4
3
[2, 3]
3.03
Line-by-line explanation
  1. Line 3The mean, 20 / 5 = 4, is pulled up by the 10-hour delivery.
  2. Line 4The median, 3, describes a typical delivery better.
  3. Line 5Two values tie as most frequent, so multimode() returns both.
  4. Line 6The population standard deviation, the version feature scalers use.
Example 2

Scaling with training statistics only

Python
from statistics import mean, median, multimode, pstdev

train_hours = [2, 2, 3, 3, 10, 4, 3]
test_hours = [2, 5, 12]

mu, sigma = mean(train_hours), pstdev(train_hours)
print(f"train mean {mu:.2f}, median {median(train_hours)}, mode {multimode(train_hours)}, sd {sigma:.2f}")

scale = lambda h: round((h - mu) / sigma, 2)
print("scaled train:", [scale(h) for h in train_hours])
print("scaled test: ", [scale(h) for h in test_hours])

baseline_abs = median(train_hours)
mae = mean(abs(h - baseline_abs) for h in test_hours)
print(f"median baseline {baseline_abs} h, test MAE {mae:.2f} h")
Output
train mean 3.86, median 3, mode [3], sd 2.59
scaled train: [-0.72, -0.72, -0.33, -0.33, 2.37, 0.06, -0.33]
scaled test:  [-0.72, 0.44, 3.15]
median baseline 3 h, test MAE 4.00 h
Line-by-line explanation
  1. Line 6Mean and standard deviation come from the training rows only.
  2. Line 11Test rows are scaled with the training statistics; the 12-hour delivery gets a z-score above 3, flagging it as far outside the training range.
  3. Lines 13 to 14The median baseline and absolute error belong together; any model must beat 4.00 hours on this test set.

Common Mean, Median, Mode and Deviation Mistakes

Scaling before splitting the data

Don't
X_scaled = StandardScaler().fit_transform(X)          # uses test rows' statistics
X_train, X_test = train_test_split(X_scaled)
Do
X_train, X_test = train_test_split(X)
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)

Judging a classifier by accuracy alone

Don't
print("accuracy:", accuracy)       # 0.92 sounds good
Do
majority_share = y_test.value_counts(normalize=True).max()
print(f"accuracy {accuracy:.2f} vs always-majority baseline {majority_share:.2f}")

Mean, Median, Mode and Deviation in Real Projects

Summary statistics in ML workflows

Every ML project starts with a profile of its data: df.describe() in pandas gives count, mean, standard deviation and quartiles for each column in one call. Teams record the training statistics alongside the model, because the same scaling must be applied in production, and monitoring compares live feature means and standard deviations with the training values to detect drift, a sign the model may need retraining.

Baselines built from these statistics are reported next to every model metric in serious evaluations, so a reader can see how much the model actually adds.

Mean, Median, Mode and Deviation FAQ

What is a z-score?

A z-score expresses a value as the number of standard deviations it lies from the mean: (value − mean) ÷ standard deviation. A z-score of 2 means two standard deviations above average. Standardising features converts them all to z-scores.

Do I need to scale features for every model?

No. Distance- and gradient-based models such as k-nearest neighbours, k-means, SVMs, regularised linear models and neural networks need scaling. Tree-based models such as decision trees, random forests and gradient boosting don't.

Should I fill missing values with the mean or the median?

For skewed numeric features, the median is usually safer because outliers don't pull it. For roughly symmetric features, either works. For categories, use the mode or a separate "missing" category. Compute the fill value on training data only.

Why fit the scaler on training data only?

The test set stands in for future data you haven't seen. If its values influence the mean and standard deviation used for scaling, information leaks into training and test scores become optimistic. Fit on training data, then apply the same transformation to everything else.

What is the difference between StandardScaler and MinMaxScaler?

StandardScaler subtracts the mean and divides by the standard deviation, giving mean 0 and standard deviation 1. MinMaxScaler maps values into a fixed range such as 0 to 1 using the minimum and maximum, which makes it sensitive to outliers.

Mean, Median, Mode and Deviation Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

What does multimode help represent?

Multiple choicemedium

Which review concern is valid for mean, median, mode and deviation?

Mean, Median, Mode and Deviation Quiz

2 questions to check what you learned.

  1. What does multimode help represent?

    • Only the arithmetic average
    • Ties among most frequent values
    • Python ignores the distinction
  2. Which statement correctly describes standard deviation?

    • Standard deviation expresses spread in the original measurement units.
    • Only the example output matters, not the rule
    • Every operation has the same behavior