DS Outliers
An outlier is an observation that lies far from the others. It might be an error (a typo, a broken sensor), or a real but rare event (a city festival that doubled rentals). Errors should be fixed or removed; real events are often the most interesting data you have. Telling the two apart needs judgement — the methods below only flag candidates.
A dataset with surprises
We take the Riverside Bikes data and add three unusual days: a festival, a data-entry error, and a terminal outage.
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
bikes.loc[20, "rides"] = 980 # river festival
bikes.loc[33, "rides"] = 3460 # typo: should be 346
bikes.loc[2, "rides"] = 12 # payment terminal outage
print(bikes["rides"].describe().round(1))count 60.0
mean 406.9
std 424.5
min 12.0
25% 260.8
50% 364.5
75% 446.2
max 3460.0
Name: rides, dtype: float64
The maximum of 3460 is clearly impossible for a service whose normal days have 120–570 rides, and the mean has jumped well above the median.
Method 1: z-scores
A z-score says how many standard deviations a value lies from the mean. A common rule flags |z| > 3. The problem: outliers inflate the mean and SD themselves, so they can hide each other (masking).
Method 2: the IQR rule
The box-plot rule flags values below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR. Quartiles barely move when a few extreme values are added, so this rule is more robust:
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
bikes.loc[20, "rides"] = 980
bikes.loc[33, "rides"] = 3460
bikes.loc[2, "rides"] = 12
r = bikes["rides"]
z = (r - r.mean()) / r.std()
print("z-score flags (|z| > 3):", list(bikes.loc[z.abs() > 3, "date"].dt.strftime("%m-%d")))
q1, q3 = r.quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"IQR fences: {low:.1f} to {high:.1f}")
flags = bikes[(r < low) | (r > high)]
print(flags[["date", "temp_c", "rides"]])z-score flags (|z| > 3): ['05-04']
IQR fences: -17.5 to 724.5
date temp_c rides
20 2024-04-21 23.7 980
33 2024-05-04 13.6 3460
The z-score rule finds only the typo: the huge value inflated the SD so much that the festival (980) no longer looks extreme. The IQR rule catches the typo and the festival. Neither catches the outage day (12 rides) — it is low, but not far below the quietest real days.
Method 3: outliers relative to a model
Some outliers are only unusual given the circumstances. Twelve rides on a cold, wet day would be plausible; on a warm, dry day it isn't. Fitting a model and looking at large residuals finds such contextual outliers:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
bikes.loc[20, "rides"] = 980
bikes.loc[33, "rides"] = 3460
bikes.loc[2, "rides"] = 12
# fix the known typo first, then model
bikes.loc[33, "rides"] = 346
model = smf.ols("rides ~ temp_c + rain_mm + weekend", data=bikes).fit()
std_resid = model.get_influence().resid_studentized_external
bikes["std_resid"] = std_resid.round(1)
print(bikes.loc[np.abs(std_resid) > 3, ["date", "temp_c", "rain_mm", "rides", "std_resid"]]) date temp_c rain_mm rides std_resid
2 2024-04-03 26.3 0.0 12 -6.2
20 2024-04-21 23.7 0.0 980 7.3
Studentized residuals are residuals scaled to be comparable across observations; values beyond ±3 are strong candidates. Now both remaining problem days stand out: the festival (far more rides than the weather predicts) and the outage (far fewer).
What to do with an outlier
| Situation | Action |
|---|---|
| Clear error with a known correction (typo 3460 → 346) | Fix it, note it |
| Clear error, no correction (outage day) | Remove it or mark it missing, note it |
| Real but rare event (festival) | Keep it; consider a flag variable (event = 1), or analyse separately |
| Unsure | Run the analysis with and without it and report both |
How much do these three days matter? A lot:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
clean = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
dirty = clean.copy()
dirty.loc[20, "rides"] = 980
dirty.loc[33, "rides"] = 3460
dirty.loc[2, "rides"] = 12
flagged = dirty.copy()
flagged.loc[33, "rides"] = 346 # fix the typo
flagged = flagged.drop(index=2) # drop the outage day
flagged["event"] = (flagged.index == 20).astype(int) # flag the festival
for name, df, f in [("clean data", clean, "rides ~ temp_c"),
("with outliers", dirty, "rides ~ temp_c"),
("treated", flagged, "rides ~ temp_c + event")]:
m = smf.ols(f, data=df).fit()
print(f"{name:14} slope={m.params['temp_c']:6.2f} R2={m.rsquared:.3f}")clean data slope= 12.54 R2=0.726
with outliers slope= 8.39 R2=0.021
treated slope= 12.35 R2=0.835
Three bad days out of 60 distort the temperature slope and wreck R². After treating them, the estimates are back close to those from the clean data.
Note: Never delete outliers just because they make the results look worse. Every removal needs a reason you'd be comfortable explaining.
Test yourself
Why can a single huge outlier hide other outliers when using z-scores?
- z-scores ignore large values
- It inflates the mean and standard deviation, making other values look less extreme
- z-scores only work on small data
- It changes the median
Q1 = 260, Q3 = 440. Above which value does the IQR rule flag outliers?
- 440
- 530
- 710
- 620
A day with a real city festival had double the usual rides. What's usually the best treatment?
- Delete it silently
- Keep it and add an event flag (or analyse it separately)
- Replace it with the mean
- Set it to zero