TExcelTAD
Home › Machine Learning › ML Mean Median Mode

ML Mean Median Mode

Before training any model you need to describe your data. The first question is usually: what is a typical value? Statistics offers three classic answers:

Measure Definition Good for
Mean The sum of all values divided by how many there are Symmetric data without extreme values
Median The middle value once the data is sorted Data with outliers (incomes, house prices)
Mode The value that appears most often Categories and repeated whole numbers

We'll use one small data set throughout: the number of minutes 11 pizza deliveries took on a Friday evening.

text
28, 35, 31, 22, 31, 40, 26, 31, 58, 29, 33

Mean

The mean (also called the average) adds everything up and divides by the count. NumPy's mean() does that in one call:

python · try it yourself
import numpy as np

minutes = np.array([28, 35, 31, 22, 31, 40, 26, 31, 58, 29, 33])

total = minutes.sum()
count = len(minutes)
print("sum:", total, " count:", count)
print("mean by hand:", total / count)
print("np.mean:     ", np.mean(minutes))
sum: 364  count: 11
mean by hand: 33.09090909090909
np.mean:      33.09090909090909

Median

The median is the value in the middle after sorting. With 11 values, the middle one is the 6th. If the count were even, the median would be the average of the two middle values.

python · try it yourself
import numpy as np

minutes = np.array([28, 35, 31, 22, 31, 40, 26, 31, 58, 29, 33])
print("sorted:", np.sort(minutes))
print("median:", np.median(minutes))

# with an even number of values the two middle ones are averaged
four = np.array([10, 20, 30, 40])
print("median of", four, "=", np.median(four))
sorted: [22 26 28 29 31 31 31 33 35 40 58]
median: 31.0
median of [10 20 30 40] = 25.0

Why the median matters: outliers

One delivery took 58 minutes (the driver got lost). That single outlier pulls the mean upward, but the median barely notices it. Watch what happens if the lost driver had taken two hours instead:

python · try it yourself
import numpy as np

normal_day = np.array([28, 35, 31, 22, 31, 40, 26, 31, 58, 29, 33])
bad_day = normal_day.copy()
bad_day[8] = 120          # the lost driver took 2 hours

for name, data in [("normal", normal_day), ("bad", bad_day)]:
    print(f"{name:6}  mean = {np.mean(data):6.2f}   median = {np.median(data):5.1f}")
normal  mean =  33.09   median =  31.0
bad     mean =  38.73   median =  31.0

The mean jumped by more than five minutes; the median stayed at 31. That is why news reports quote median household income: a few billionaires would distort the mean.

Mode

The mode is the most common value. NumPy has no mode function, but SciPy's stats module does, and Python's built-in statistics module works too:

python · try it yourself
import numpy as np
from scipy import stats
import statistics

minutes = np.array([28, 35, 31, 22, 31, 40, 26, 31, 58, 29, 33])

result = stats.mode(minutes)
print("scipy mode:", result.mode, "appears", result.count, "times")
print("statistics.mode:", statistics.mode(minutes.tolist()))

# for text categories, pandas value_counts shows every frequency
import pandas as pd
toppings = pd.Series(["cheese", "ham", "cheese", "veggie", "cheese", "ham"])
print(toppings.value_counts())
print("most popular:", toppings.mode()[0])
scipy mode: 31 appears 3 times
statistics.mode: 31
cheese    3
ham       2
veggie    1
Name: count, dtype: int64
most popular: cheese

For continuous measurements (like 21.73 °C) the mode is rarely useful, because almost every value is unique. It shines with categories and small whole numbers.

All three with pandas

In real projects your data usually lives in a pandas DataFrame. Columns have .mean(), .median() and .mode() methods, and .describe() prints a quick summary:

python · try it yourself
import pandas as pd

orders = pd.DataFrame({
    "minutes": [28, 35, 31, 22, 31, 40, 26, 31, 58, 29, 33],
    "pizzas":  [1, 2, 1, 1, 3, 2, 1, 1, 4, 2, 1],
})
print("mean:  ", orders["minutes"].mean().round(2))
print("median:", orders["minutes"].median())
print("mode:  ", orders["pizzas"].mode().tolist())
print()
print(orders.describe().round(2))
mean:   33.09
median: 31.0
mode:   [1]

       minutes  pizzas
count    11.00   11.00
mean     33.09    1.73
std       9.49    1.01
min      22.00    1.00
25%      28.50    1.00
50%      31.00    1.00
75%      34.00    2.00
max      58.00    4.00

The 50% row of describe() is the median — the next lessons explain the other rows (std, 25%, 75%).

Tip: Compare the mean and the median of a column. If they are far apart, the data is skewed or has outliers, and you should look at it more closely before modelling.

Test yourself

What is the median of [3, 9, 4, 7]?

  1. 4
  2. 5.5
  3. 5.75
  4. 7

A data set contains one huge outlier. Which measure of the typical value is least affected?

  1. Mean
  2. Median
  3. Sum
  4. Maximum

Which measure is the most natural choice for a column of favourite colours?

  1. Mean
  2. Median
  3. Mode
  4. Standard deviation