Calculate the median value of a dataset used in model feature analysis.
The median is the middle value of a sorted dataset. For an odd number of values, it's the exact middle element; for an even number, it's the average of the two middle elements. Unlike the mean, the median is robust to outliers — it depends only on the rank order of values, not their magnitude, making it a preferred central-tendency metric for skewed data or datasets contaminated with extreme values.
median = sorted[n/2] (odd n) or (sorted[n/2 - 1] + sorted[n/2]) / 2 (even n)
When a feature's distribution is skewed or contains outliers (e.g. income, latency, file size), the median gives a more representative 'typical value' than the mean, which outliers can pull heavily in one direction.
Yes — computing the median requires the data to be sorted (or an equivalent selection algorithm) to identify the middle value(s), unlike the mean which can be computed in a single pass without sorting.
Duplicates are treated like any other value — they're included in the sort and counted normally; the median calculation doesn't change based on how many duplicates exist.
It's resistant to outlier magnitude (an outlier of 1000 vs. 10000 has the same effect on the median) but not to outlier proportion — if more than half the data is contaminated, the median itself becomes unreliable.