Robust Scaling With the Median and IQR

Feature EngineeringMedium+15 XP+15

Robust Scaling With the Median and IQR

Z-score standardization divides by the standard deviation — a number that one wild outlier can inflate enormously. When that happens, every ordinary value gets squashed into a narrow band near zero, and the scaling has destroyed the structure it was supposed to reveal.

Robust scaling replaces both ingredients with order statistics, which outliers can't move:

scaled=v−medianIQR,IQR=Q3−Q1scaled = \frac{v - \text{median}}{IQR}, \qquad IQR = Q_3 - Q_1scaled=IQRv−median​,IQR=Q3​−Q1​

Task: write robust_scale(values) returning the scaled values, each rounded to 4 decimal places.

For the median and the two quartiles, use the same linear-interpolation rule as the percentile problem — on the sorted values:

position=(n−1)×p100\text{position} = (n - 1) \times \frac{p}{100}position=(n−1)×100p​

interpolating between the neighbouring values when the position isn't a whole number. The median is p = 50, Q1 is p = 25, Q3 is p = 75.

  • If the IQR is 0, return a list of 0.0. That happens when the middle half of the data is a single repeated value, and there's no spread to divide by.
  • After scaling, the median sits at exactly 0 and the quartiles at roughly -0.5 and +0.5.

The outlier doesn't vanish — and shouldn't. Run [1, 2, 3, 4, 100] through this and the four ordinary values come out neatly spread between -1 and 0.5, while the outlier lands at 48.5. That's the right behaviour: the typical values are on a readable scale and the anomaly is still visibly anomalous. Z-scoring the same list compresses the ordinary four into a sliver around -0.5 and reports the outlier as a mere 2.0.

Examples

values = [1, 2, 3, 4, 5]
returns [-1.0, -0.5, 0.0, 0.5, 1.0]
values = [1, 2, 3, 4, 100]
returns [-1.0, -0.5, 0.0, 0.5, 48.5]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run