Median
- Machine Learning course
- Beginner
- Lesson 26/112
- 5 min
The median is the middle value when data is sorted.
Median
The median is the middle value when the values are sorted; with an even count it is the mean of the two middle ones.
x = np.array([3, 1, 100, 2, 4])
print(np.median(x)) # 3.0 sorted: 1 2 3 4 100
print(x.mean()) # 22.0The median isn't affected by outliers; for skewed distributions like income or house prices it is better than the mean as a "typical value".
Percentiles and mode
The median is the 50th percentile. Other percentiles describe the shape of the distribution:
x = np.arange(1, 101)
print(np.percentile(x, [25, 50, 75])) # [25.75 50.5 75.25]
vals, counts = np.unique([2, 3, 3, 5, 3], return_counts=True)
print(vals[counts.argmax()]) # 3 (mode: most frequent value)The mode is used to fill missing values in categorical data (strategy="most_frequent").
Practice Outlier-robust centre
Print the mean and the median of the gelir array separated by a space; see the difference.
Starter code
import numpy as np
gelir = np.array([20, 22, 25, 23, 210])
# buraya yazSample solution
import numpy as np
gelir = np.array([20, 22, 25, 23, 210])
print(gelir.mean(), np.median(gelir))Expected output
60.0 23.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>np.median([5, 1, 3, 7])</code>?
- 4.0 Correct answer
- 3.0
- 5.0
- 4.5
Explanation: Sorted: 1 3 5 7; the mean of the middle two (3 and 5) is 4.
2 Compute the median.
m = np.____(x)
m = np.median(x)
Explanation: For NumPy arrays median isn't a method; it is the np.median function.
3 Match the measures.
| Term | Meaning |
|---|---|
mean |
Sum / count |
median |
Middle sorted value |
mode |
Most frequent value |
75th percentile |
Upper quartile boundary |