Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Machine Learning Notes
Topic #324

Median

The median is the middle value of a dataset once it's sorted — exactly half the values fall below it, and half above. Unlike the mean, it only cares about rank, not magnitude, which makes it far more resistant to outliers.

What "Only Cares About Rank" Actually Means

If you took the single largest value in a dataset and made it ten times bigger, the mean would shift substantially — but the median wouldn't move at all, because that value was already the largest, and making it "even more the largest" doesn't change its rank position. This single property is why the median is the standard choice for summarizing skewed real-world data like income, house prices, or wait times.

Formula / Definition

\[ \text{Median} = \begin{cases} x_{\left(\frac{n+1}{2}\right)} & \text{if } n \text{ is odd} \\[6pt] \dfrac{x_{(n/2)} + x_{(n/2 + 1)}}{2} & \text{if } n \text{ is even} \end{cases} \]

Here \(x_{(k)}\) means "the \(k\)-th value after sorting the data in ascending order," and \(n\) is the number of data points. Sort first — always — the formula only works on sorted data.

Graphical Intuition

median 3 values below 3 values above (of 7 total)

The median splits the sorted data exactly in half by count — regardless of how far the extreme values are from the center.

Step-by-Step Numerical Example — Odd Count

Seven students' exam scores, already sorted: \(62, 68, 68, 72, 75, 80, 85\).

StepCalculation
1. Confirm sorted order62, 68, 68, 72, 75, 80, 85 — already sorted
2. Count\(n=7\) (odd)
3. Find position\((n+1)/2 = 4\)th value
4. Read the valueThe 4th value is \(72\)

Step-by-Step Numerical Example — Even Count

Add one more score, 90: \(62, 68, 68, 72, 75, 80, 85, 90\) (\(n=8\), even).

\[ \text{Median} = \frac{x_{(4)} + x_{(5)}}{2} = \frac{72 + 75}{2} = 73.5 \]

The Income Example, Revisited

Recall the incomes \([30000, 32000, 35000, 40000, 500000]\) from the Mean note, where the mean was ₹127,400 — misleadingly high. Sorted, these are already in order; the middle (3rd of 5) value is \(35000\). The median, ₹35,000, is a far more representative "typical" income than the mean.

Python Implementation

# From scratch
def median_from_scratch(data):
    sorted_data = sorted(data)
    n = len(sorted_data)
    mid = n // 2
    if n % 2 == 1:
        return sorted_data[mid]
    else:
        return (sorted_data[mid - 1] + sorted_data[mid]) / 2

scores = [62, 68, 68, 72, 75, 80, 85]
print(median_from_scratch(scores))   # 72

# NumPy / Pandas
import numpy as np
import pandas as pd

print(np.median(scores))              # 72.0
print(pd.Series(scores).median())      # 72.0

incomes = [30000, 32000, 35000, 40000, 500000]
print(np.mean(incomes), np.median(incomes))   # 127400.0  35000.0 -- the gap IS the story

Median vs Mean — When Each Wins

SituationBetter ChoiceWhy
Symmetric data, no outliersMeanUses full information, has useful mathematical properties
Skewed data (income, prices, wait times)MedianRobust — one extreme value can't drag it away from "typical"
Ordinal categorical dataMedianRank-based, works without needing true numeric distances between categories

Practical Use Cases

  • Reporting "typical" values for skewed business metrics — median household income, median time-to-resolution for support tickets
  • Median imputation for missing values in skewed numeric features
  • Computing \(Q1\) and \(Q3\) (the 25th/75th percentiles) for IQR-based outlier detection — the median is the 50th percentile, the same family of calculation

Advantages

  • Robust to outliers — resistant to even extremely large or small values
  • Meaningful for ordinal data, where "distance" between values isn't well-defined but rank is

Limitations

  • Ignores the actual magnitude of values beyond their rank — two very different datasets can share the same median
  • Less useful mathematically inside optimization — many algorithms are built around minimizing squared error (which relates to the mean), not absolute rank-based error

Common Mistakes

  • Computing the median without sorting first — the formula only makes sense on sorted data; unsorted input silently gives a meaningless answer.
  • Applying the odd-count formula to an even-count dataset (or vice versa) — always check \(n\)'s parity first.
  • Assuming the median is always "better" than the mean — for symmetric, outlier-free data, the mean typically carries more usable information.

Interview Relevance

Q: "Why does Zillow (or any real-estate platform) report median home price, not average?" A handful of ultra-luxury homes would drag the average far above what a typical buyer actually experiences; the median stays representative of the "middle" home regardless of how extreme the priciest listings get.

Q: "How would you decide whether to impute a missing numeric feature with its mean or its median?" Check the feature's distribution for skew and outliers first (a quick histogram or comparing mean vs median directly) — if they're close, either works; if the mean is noticeably pulled away from the median, use the median.

Practice Question

For the dataset \([5, 100, 6, 7, 8]\), sort it, then compute the median by hand. Compare it to the mean and explain the gap.

Related ML Notes

Want to go beyond the notes?

Join CodingNow's Machine Learning course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →