Statistics Median
The median is the middle value of a dataset once it is sorted in order, and it is often a more reliable measure of a 'typical' value when the data includes outliers.
What Is the Median?
To find the median, sort all the values from smallest to largest and pick the value that sits exactly in the middle. Half of the data lies at or below the median, and half lies at or above it. How you locate that middle value depends on whether you have an odd or an even number of data points.
Finding the Median: Odd Number of Values
Consider five house prices, in thousands of dollars: 150, 165, 172, 180, and 950 (already sorted). With 5 values, the median is simply the 3rd value, since there are exactly two values below it and two above it. The median house price is 172 (thousand dollars).
Example
prices_in_thousands = [180, 150, 172, 165, 950]
prices_in_thousands.sort()
print(prices_in_thousands)
# [150, 165, 172, 180, 950]
middle_index = len(prices_in_thousands) // 2
median = prices_in_thousands[middle_index]
print("Median:", median)
# Median: 172Finding the Median: Even Number of Values
If instead there were only four houses priced at 150, 165, 172, and 180 (thousand dollars), there is no single middle value - so the median is the average of the two middle values, 165 and 172: (165 + 172) / 2 = 168.5.
Example
import statistics
prices_in_thousands = [150, 165, 172, 180]
print("Median (even count):", statistics.median(prices_in_thousands))
# Median (even count): 168.5
all_five_prices = [150, 165, 172, 180, 950]
print("Median (odd count):", statistics.median(all_five_prices))
# Median (odd count): 172Median vs Mean with Skewed Data
- Sort the data from smallest to largest.
- If there is an odd number of values, the median is the single middle value.
- If there is an even number of values, the median is the average of the two middle values.