Module 2 · Beginner · Describing data

Mean, median and mode explained

Mean, median and mode with a start-up's salaries: the mean as a balance point, why one outlier drags it, the weighted mean behind your CGPA, and which to use.

By theprogrammers team · · 11 min read

A small start-up in Pune has nine people. Eight of them earn between ₹35,000 and ₹90,000 a month. The founder pays herself ₹6 lakh. Ask "what does a typical person here earn?" and you can get two very different honest answers: about ₹1.2 lakh, or ₹60,000. The first is the mean, the second the median, and the gap between them tells you something important about the data.

Mean, median and mode are three ways to answer the same question: what's a typical value? Each one has a different idea of "typical", and each one is right for different data. Knowing which to use, and why they disagree, matters more than knowing how to calculate them. Python will do the calculating.

What you need first: types of data. Mean, median and mode open the "describing data" module.

Key terms

  • Measure of centre (or central tendency): a single number that represents a typical value.
  • Mean: the sum of the values divided by how many there are. The everyday "average".
  • Median: the middle value when the values are sorted.
  • Mode: the value that appears most often.
  • Outlier: a value far from most of the others.
  • Weighted mean: a mean where some values count more than others.
  • Skewed data: data with a long tail on one side, such as a few very high salaries.

Nine salaries, two answers

Here are the monthly salaries, in rupees:

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

salaries = pd.Series(
    [35_000, 42_000, 48_000, 55_000, 60_000, 62_000, 75_000, 90_000, 600_000],
    index=["Ravi", "Neha", "Arjun", "Sana", "Kabir", "Meera", "Dev", "Ahana", "Founder"],
)
print("mean:  ", round(salaries.mean()))
print("median:", round(salaries.median()))
mean:   118556
median: 60000

Eight of the nine people earn less than the mean, ₹1,18,556. As a description of a typical salary here, the mean is plainly misleading. The median, ₹60,000, is what Kabir earns, and four people earn less and four earn more. That's a much better picture of a typical employee.

The mean: a balance point

To get the mean, add everything up and share it equally: (35,000 + 42,000 + … + 6,00,000) ÷ 9 = ₹1,18,556. It's the salary everyone would get if the total pay were split evenly.

The formula, as a summary: for n values x₁, x₂, …, xₙ, the mean is

x̄ = (x₁ + x₂ + … + xₙ) ÷ n = Σx ÷ n

Read it as "x-bar equals the sum of the values divided by how many there are". (Σ means "add up"; see summation notation.)

There's a useful picture of the mean. Put each value on a number line as a weight on a seesaw. The mean is the point where the seesaw balances. A value far out on one side has a long lever, so it pulls the balance point a long way towards it. That's what the founder's salary does. Here's the picture:

fig, ax = plt.subplots(figsize=(9, 3))
ax.scatter(salaries / 1000, np.zeros(9), s=120, color="#d9a05a", zorder=3)
ax.axvline(salaries.mean() / 1000, color="#c2410c", linewidth=2.5, label=f"mean: ₹{salaries.mean() / 1000:.0f}k")
ax.axvline(salaries.median() / 1000, color="#0f766e", linewidth=2.5, linestyle="--", label=f"median: ₹{salaries.median() / 1000:.0f}k")
ax.annotate("founder", (600, 0), textcoords="offset points", xytext=(-20, 12))
ax.set_yticks([])
ax.set_xlabel("Monthly salary (₹ thousand)")
ax.set_title("One very high salary drags the mean away from everyone else")
ax.legend(loc="upper center")
plt.show()
Nine dots on a horizontal salary line. Eight are bunched between 35 and 90 thousand rupees; the founder's dot sits alone far to the right at 600 thousand. A dashed teal line marks the median at 60 thousand, in the middle of the bunch. A solid orange line marks the mean at about 119 thousand, to the right of all eight bunched dots.

The mean sits in an empty stretch of the line, to the right of every employee except the founder. It's being pulled by the one dot far away.

Experiment: move the outlier

Predict what happens to the mean and the median if the founder's salary doubles to ₹12 lakh, then run it:

richer = salaries.copy()
richer["Founder"] = 1_200_000
print("mean:  ", round(richer.mean()))
print("median:", round(richer.median()))
mean:   185222
median: 60000

The mean jumps by about ₹67,000. The median doesn't move at all: Kabir is still in the middle. The median only cares about order, not how far away the extreme values are. That's why it's called robust to outliers.

The median: the middle value

To find the median, sort the values and take the middle one. With 9 values, the middle is the 5th: four below, four above. With an even number of values, there are two middle values, and the median is halfway between them:

print(pd.Series([3, 8, 1, 9]).median())
5.5

Sorted, the values are 1, 3, 8, 9. The two middle values are 3 and 8, and halfway between them is 5.5.

The median splits the data into two equal halves. That's why house prices, incomes and waiting times are usually reported as medians: those kinds of data have a few very large values that would drag a mean upwards.

The mode: the most common value

The mode is the value that appears most often. For a shoe shop, the mean shoe size sold (say 8.37) is useless, because nobody wears size 8.37. The mode tells the shop which size to stock most of:

shoe_sizes = pd.Series([7, 8, 8, 9, 10, 8, 7, 9, 8, 11, 10, 8])
print(shoe_sizes.mode())
print(shoe_sizes.value_counts().head(3))
0    8
dtype: int64
8    5
7    2
9    2
Name: count, dtype: int64

mode() returns a Series because data can have more than one mode (two values tied for most common). The mode is the only one of the three that works for nominal categories: the most popular payment method or the most common blood group. You can't take the mean or median of "UPI, cash, card".

When the mean and median agree

The salaries were extreme. In many real measurements, the mean and median are close. Here are penguin body masses again:

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")
summary = penguins.groupby("species")["body_mass_g"].agg(["mean", "median"]).round(0)
print(summary)
             mean  median
species                  
Adelie     3701.0  3700.0
Chinstrap  3733.0  3700.0
Gentoo     5076.0  5000.0

Within each species, the mean and median are within about 80 g of each other. When weights spread out evenly on both sides of the middle (data called symmetric), the balance point and the middle value land in nearly the same place. So the gap between the mean and the median is a quick test of shape:

  • Mean ≈ median: roughly symmetric data. Either works; the mean is more common.
  • Mean much bigger than median: a long tail of high values (right-skewed), like salaries.
  • Mean much smaller than median: a long tail of low values (left-skewed), like marks in an easy exam where most score high and a few score very low.

The weighted mean: your CGPA

Sometimes values shouldn't count equally. A semester's grade point average gives more weight to courses with more credits:

grade_points = np.array([9, 7, 10, 8])     # maths, physics, lab, English
credits = np.array([4, 4, 2, 3])
print("plain mean:   ", grade_points.mean().round(2))
print("weighted mean:", np.average(grade_points, weights=credits).round(2))
plain mean:    8.5
weighted mean: 8.31

np.average(..., weights=credits) multiplies each grade point by its credits, adds them up and divides by the total credits: (9 × 4 + 7 × 4 + 10 × 2 + 8 × 3) ÷ 13 = 108 ÷ 13 ≈ 8.31. The weighted mean is lower than the plain mean because the 10 came from the 2-credit lab, which counts for less, and the 7 from a 4-credit course, which counts for more.

Which one should you use?

DataBest measure of centreWhy
Symmetric numbers, no big outliers (heights, penguin weights)MeanUses every value; works well in further maths
Skewed numbers or outliers (salaries, house prices, delivery times)MedianIsn't dragged by extreme values
Nominal categories (city, payment method)ModeThe only one that makes sense
Ordinal categories (ratings, sizes)Median or modeThey have an order but no measured gaps
Values that matter unequally (credits, sample sizes)Weighted meanGives each value its proper weight

When in doubt, report both the mean and the median. If they differ a lot, say so: the gap is itself useful information.

Where machine learning uses them

  • Filling missing values: SimpleImputer(strategy="median") fills gaps with the median, which isn't thrown off by outliers. strategy="most_frequent" uses the mode for categories.
  • Baselines: the simplest regression model predicts the mean of the training targets for everyone. Any real model must beat it. For classification, the baseline predicts the mode, the most common class.
  • Loss functions: a model trained to minimise squared error is pulled towards the mean, and one trained to minimise absolute error is pulled towards the median. That's why absolute error is less sensitive to outliers.

Common mistakes

  • Using the mean on skewed data. It describes nobody. Check the median too.
  • Forgetting to sort before finding the median by hand. The median is the middle of the sorted values.
  • Treating the mode as useful for continuous data. With precise measurements such as 3,712.4 g, every value may appear once, so the mode means little. Group the values into ranges first, or use the median.
  • Averaging averages. The mean of two class averages is only the overall average if the classes are the same size. Otherwise use a weighted mean.

Practice

  1. Find the mean, median and mode of 4, 7, 7, 2, 10 by hand.
Show the answer

Mean: (4 + 7 + 7 + 2 + 10) ÷ 5 = 30 ÷ 5 = 6. Sorted: 2, 4, 7, 7, 10, so the median is 7. The mode is 7, which appears twice.

  1. Predict, then check: if the founder leaves the start-up, what happens to the mean and the median salary?
Show the answer
staff = salaries.drop("Founder")
print(round(staff.mean()), round(staff.median()))
58375 57500

The mean drops by about ₹60,000 and now sits close to the median, which barely changes. Without the outlier, the data is roughly symmetric.

  1. A class of 30 averages 72 marks, and a class of 10 averages 92. A student says the combined average is (72 + 92) ÷ 2 = 82. What's wrong, and what's the right answer?
Show the answer

The classes are different sizes, so the plain mean of the two averages is wrong. The weighted mean is (30 × 72 + 10 × 92) ÷ 40 = (2,160 + 920) ÷ 40 = 77.

  1. Which measure of centre would you report for: (a) the waiting time for a doctor's appointment, where most waits are short and a few are weeks long; (b) the most popular pizza topping; (c) the heights of students in a class?
Show the answer

(a) The median: waiting times are right-skewed. (b) The mode: toppings are nominal categories. (c) The mean: heights are roughly symmetric.

  1. Explain in your own words why the median didn't change when the founder's salary doubled, but the mean did.
Show the answer

The median depends only on which value is in the middle of the sorted list. Doubling the top salary keeps it at the top, so the middle person is still Kabir. The mean adds up every value, so a bigger top salary adds straight to the total.

Interview questions

When would you use the median instead of the mean?

When the data is skewed or contains outliers, such as income, house prices or response times, because the median is robust to extreme values while the mean is pulled towards them. The median is also suitable for ordinal data.

What value minimises squared error, and what value minimises absolute error?

For a constant prediction, the mean minimises the sum of squared errors, and the median minimises the sum of absolute errors. This is why MSE-trained models are more sensitive to outliers than MAE-trained ones.

Key takeaways

  • The mean is the balance point: it uses every value and is pulled towards outliers.
  • The median is the middle of the sorted values: robust to outliers and best for skewed data.
  • The mode is the most common value, and the only centre for nominal categories.
  • If the mean and median differ a lot, the data is skewed; report both.
  • Use a weighted mean when values count unequally, such as credits in a CGPA.

Frequently asked questions

Is "average" the mean or the median?

In everyday speech, "average" almost always means the mean. In statistics, prefer the precise words, because news reports sometimes use "average" for the median, especially for incomes and house prices.

What's a trimmed mean?

A mean that ignores a small percentage of the highest and lowest values, such as the top and bottom 10%. It sits between the mean and the median: it uses most of the data but isn't dragged by extremes. Some sports scoring drops the highest and lowest judges' marks for the same reason.

Can data have no mode?

If every value appears exactly once, there's no single most common value. Pandas then returns every value as a mode. For continuous measurements, group the values into ranges and find the most common range instead.

What to learn next

  1. Measure how much values vary in range, variance and standard deviation.
  2. Revisit the Σ sign in summation notation.
  3. See the baseline models that predict the mean in the machine learning workflow.