Data analysis · Intermediate · 17 min
Find outliers in your data and decide what to do with them
By Padding · Updated 18 Nov 2026
Python 3.15 · pandas 3.1.1 · NumPy 2.5.5 · matplotlib 3.11.2 · uv 0.13 (checked on python:3.15-slim)
You will find unusual values in a table of 600 ride fares with a box plot, the IQR rule, robust z-scores and fare-policy rules, sort them into data errors and real extremes, measure what deleting, capping and keeping them does to the results, and write a short report that gives the median beside the mean.
On this page
An outlier is a value far from the rest. That is all the word means. It does not tell you whether the value is wrong. A fare of KES 7,200 for a 12 km trip is probably a typing slip; a fare of KES 2,380 for a 38 km airport run is a good night for the driver. Treat both the same way and you either keep a mistake or throw away real money.
So handling outliers is two jobs. First, find the unusual values, with methods that are not fooled by the outliers themselves. Then decide, row by row, which are errors and which are real, using what you know about how the data was made. Statistics can do the first job. Only domain knowledge can do the second.
You will work on generated data from an invented ride-hailing service in Nairobi: 600 trips with a distance, a surge multiplier and a fare in Kenyan shillings (KES). Hidden in it are refunds keyed in as negative fares, fares typed with an extra zero, long airport runs and a few late-night surge fares. Everything runs in a throwaway folder, ~/outliers-demo, which you can delete at the end.
Step 1 · Create the project and generate the fares
Make the folder and add pandas, NumPy and matplotlib. Each range allows patch releases only, so a new minor version cannot change your numbers:
mkdir -p ~/outliers-demo
cd ~/outliers-demo
uv init --no-package --python 3.15
uv add "pandas>=3.1,<3.2" "numpy>=2.5,<2.6" "matplotlib>=3.11,<3.12"
uv run python -c "import pandas, numpy, matplotlib; print(pandas.__version__, numpy.__version__, matplotlib.__version__)"Now write make_fares.py. It uses a seeded random generator, so you get the same 600 trips every time. Read the comments: they tell you which problems are planted, which is a luxury you will not have with real data.
cat > make_fares.py <<'PY'
import numpy as np
import pandas as pd
rng = np.random.default_rng(2026)
n = 600
# Ordinary trips across the city: mostly 2 to 15 km.
distance_km = (rng.gamma(shape=2.5, scale=3.0, size=n) + 1.0).round(1)
surge = np.ones(n)
# Airport runs: real trips, much longer than the rest.
airport = rng.choice(n, size=8, replace=False)
distance_km[airport] = rng.uniform(32, 40, size=8).round(1)
# Late-night surge pricing: real trips, priced 2.5x.
night = rng.choice(np.setdiff1d(np.arange(n), airport), size=6, replace=False)
surge[night] = 2.5
tariff = 150 + 55 * distance_km
fare = (tariff * surge * rng.lognormal(0, 0.12, size=n)).round(-1)
df = pd.DataFrame({
"trip_id": [f"T{i:04d}" for i in range(1, n + 1)],
"distance_km": distance_km,
"surge": surge,
"fare_kes": fare,
})
# Data errors: refunds keyed in as negative fares, and fares typed with an extra zero.
others = np.setdiff1d(np.arange(n), np.concatenate([airport, night]))
refunds = rng.choice(others, size=4, replace=False)
df.loc[refunds, "fare_kes"] = -df.loc[refunds, "fare_kes"]
typos = rng.choice(np.setdiff1d(others, refunds), size=3, replace=False)
df.loc[typos, "fare_kes"] = df.loc[typos, "fare_kes"] * 10
df.to_csv("fares.csv", index=False)
print("rows:", len(df))
print(df.head().to_string(index=False))
PY
uv run make_fares.pyCheck it worked
The version line prints 3.1.1 2.5.5 3.11.2, or later patch releases. The script prints rows: 600 and five trips, the first being T0001, 4.6 km, surge 1.0, fare 410.0. A file fares.csv now sits in the folder.
Step 2 · Look at the spread before you test anything
Start with a summary and a picture. describe() gives you the extremes and quartiles in one go, and a box plot shows where the bulk of the fares sit and which points stand apart. Write look.py:
cat > look.py <<'PY'
import matplotlib
matplotlib.use("Agg") # write image files; no window needed
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("fares.csv")
print(df["fare_kes"].describe().round(1).to_string())
fig, ax = plt.subplots(figsize=(7, 3))
ax.boxplot(df["fare_kes"], orientation="horizontal", whis=1.5)
ax.set_xlabel("Fare (KES)")
ax.set_yticks([])
ax.set_title("Fares per trip")
fig.tight_layout()
fig.savefig("box_fares.png", dpi=150)
print("saved box_fares.png")
PY
uv run look.pyTwo numbers should stop you straight away. The minimum is −810: a fare cannot be negative. The maximum is 7,200, more than twelve times the median. You do not know yet what either is, but you know where to look.
In the box plot, the box runs from the 25th to the 75th percentile, the line inside it is the median, and the whiskers reach the furthest fares within 1.5 box-lengths of the box. Every dot beyond a whisker is a candidate outlier.
Check it worked
The summary shows min -810.0, 50% 560.0 (the median), 75% 780.0 and max 7200.0, with a mean of 655.2. Open box_fares.png: a box between roughly 420 and 780, a row of dots to the right of the upper whisker reaching out to 7,200, and four dots to the left of zero.
Step 3 · Flag unusual fares with the IQR rule
The box plot's dots come from the IQR rule, and you can compute it yourself. The interquartile range (IQR) is Q3 minus Q1, the width of the middle half of the data. Anything more than 1.5 IQRs below Q1 or above Q3 is flagged. Because quartiles ignore the extreme tails, a handful of wild values cannot drag the fences towards them. Write iqr.py:
cat > iqr.py <<'PY'
import pandas as pd
df = pd.read_csv("fares.csv")
fare = df["fare_kes"]
q1, q3 = fare.quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"Q1 {q1:.0f} Q3 {q3:.0f} IQR {iqr:.0f}")
print(f"fences: below {low:.0f} or above {high:.0f}")
below = df[fare < low]
above = df[fare > high]
print("below the lower fence:", len(below))
print("above the upper fence:", len(above))
print(" of which longer than 20 km:", int((above["distance_km"] > 20).sum()))
print(" of which surge-priced:", int((above["surge"] > 1).sum()))
print()
print(above.nlargest(5, "fare_kes").to_string(index=False))
PY
uv run iqr.pyThe rule flags 28 fares. Look at what they are, though: 18 of the 24 high ones are trips longer than 20 km, and 3 more are surge-priced. Most of what the rule calls "outliers" are long trips charged correctly. The IQR rule only knows that a number is far from the middle; it has no idea that distance explains most of that distance.
Check it worked
The script prints Q1 420 Q3 780 IQR 360 and fences of −120 and 1320, then 4 fares below the lower fence and 24 above the upper one, 18 of them longer than 20 km and 3 surge-priced. The five largest are T0591 (7,200), T0162 (3,400), T0455 (3,100), T0447 (2,530, surge 2.5) and T0140 (2,380 for 38.5 km).
Step 4 · Compare classic and robust z-scores
A z-score measures how many standard deviations a value sits from the mean, and |z| above 3 is a common cut-off. The trouble is that the mean and the standard deviation are themselves pulled by outliers. Three fares with an extra zero inflate the standard deviation so much that other unusual values start to look normal. This is called masking.
The robust z-score (also called the modified z-score) swaps the mean for the median and the standard deviation for the median absolute deviation (MAD): the median of each value's distance from the median. Multiplying by 0.6745 puts it on the same scale as an ordinary z-score for normally distributed data, and the usual cut-off is |robust z| above 3.5. Write robust_z.py:
cat > robust_z.py <<'PY'
import pandas as pd
df = pd.read_csv("fares.csv")
fare = df["fare_kes"]
# Classic z-score: distance from the mean, in standard deviations.
z = (fare - fare.mean()) / fare.std()
# Robust z-score: distance from the median, in units of the
# median absolute deviation (MAD). 0.6745 puts it on the same scale as z.
median = fare.median()
mad = (fare - median).abs().median()
robust_z = 0.6745 * (fare - median) / mad
print(f"mean {fare.mean():.0f} standard deviation {fare.std():.0f}")
print(f"median {median:.0f} MAD {mad:.0f}")
print("classic |z| > 3:", int((z.abs() > 3).sum()))
print("robust |z| > 3.5:", int((robust_z.abs() > 3.5).sum()))
print()
df["z"] = z.round(1)
df["robust_z"] = robust_z.round(1)
print(df[fare < 0].to_string(index=False))
PY
uv run robust_z.pyThe classic z-score flags 9 fares; the robust one flags 23. The table of negative fares shows why. T0291 (−440) and T0096 (−430) have a classic z of −2.4, comfortably inside the ±3 band, so the classic method calls an impossible fare normal. Their robust z-scores are −4.0 and −3.9, past the cut-off.
Neither method knows anything about fares. The robust one is harder to fool, so use it (or the IQR rule) as your default first pass, and treat the list it gives you as questions, not answers.
Check it worked
The script prints a mean of 655 with a standard deviation of 456, a median of 560 with a MAD of 170, then classic |z| > 3: 9 and robust |z| > 3.5: 23. In the table of the four negative fares, every robust_z value is −3.9 or lower, while two of the z values are −2.4.
Step 5 · Use domain rules to separate errors from real extremes
Now bring in what you know about the business. Two rules come from the (invented) fare policy:
- A fare is never negative. Refunds belong in a refunds table, not as negative trips.
- A fare is never more than the published cap: KES 250 plus 90 per km, times any surge multiplier.
A fare that breaks a rule is an error, whatever its z-score. A fare that breaks no rule but is still statistically unusual is a real extreme: keep it and know why it is there. Write label.py:
cat > label.py <<'PY'
import pandas as pd
df = pd.read_csv("fares.csv")
fare = df["fare_kes"]
# Statistical flag: robust z-score above 3.5 in either direction.
median = fare.median()
mad = (fare - median).abs().median()
unusual = (0.6745 * (fare - median) / mad).abs() > 3.5
# Domain rules from the fare policy: a fare is never negative, and never more
# than the published cap of KES 250 plus 90 per km, times any surge multiplier.
cap = (250 + 90 * df["distance_km"]) * df["surge"]
negative = fare < 0
over_cap = fare > cap
df["status"] = "typical"
df.loc[unusual, "status"] = "real extreme"
df.loc[negative | over_cap, "status"] = "error"
df["reason"] = ""
df.loc[negative, "reason"] = "negative fare"
df.loc[over_cap, "reason"] = "above tariff cap"
print(df["status"].value_counts().to_string())
print()
errors = df[df["status"] == "error"]
print(errors.to_string(index=False))
print()
extreme = df[df["status"] == "real extreme"]
print("real extremes longer than 20 km:", int((extreme["distance_km"] > 20).sum()))
print("real extremes with surge pricing:", int((extreme["surge"] > 1).sum()))
df.to_csv("fares_labelled.csv", index=False)
errors.to_csv("fare_errors.csv", index=False)
PY
uv run label.pyThe rules run last, so they override the statistical flag: the 7,200 fare is both unusual and over the cap, and it ends up as an error. Note that the rules do not need a statistical flag at all. A fare of KES 900 for a 1 km trip would break the cap while sitting close to the median, and only the rule would catch it.
fare_errors.csv holds the rows to send back to whoever owns the data, with the reason for each. Do not quietly "fix" them yourself: dividing T0591 by ten looks obvious, but only the source records can tell you whether the driver typed an extra zero or the trip really was strange.
If your data covers several countries, run each rule per currency and per city. A fare of 2,000 is ordinary in Nigerian naira and very high in Kenyan shillings, so an outlier test on mixed currencies flags the wrong rows.
Check it worked
The counts are typical 577, real extreme 16 and error 7. The error table lists four negative fares and three above the cap (T0162, T0455 and T0591). Of the 16 real extremes, 13 are longer than 20 km and 3 are surge-priced. fare_errors.csv has a header and 7 rows.
Step 6 · Compare deleting, capping and keeping the extremes
With the errors set aside, you still have 16 real but extreme fares. There are three common ways to treat them, and each changes your results differently:
- Keep them, and report statistics that are not dominated by them.
- Delete them. This is only right when they are out of scope (for example, if the analysis is about city trips and airport runs are a separate product).
- Cap them, also called winsorising: pull every value below the 1st percentile up to it, and every value above the 99th percentile down to it. This tames the mean while keeping the row count.
Write compare.py to put the raw file and all three options side by side:
cat > compare.py <<'PY'
import pandas as pd
df = pd.read_csv("fares_labelled.csv")
clean = df[df["status"] != "error"] # data errors go back to the data owner
fare = clean["fare_kes"]
low, high = fare.quantile([0.01, 0.99])
options = {
"raw file (errors in)": df["fare_kes"],
"keep extremes": fare,
"delete extremes": fare[clean["status"] == "typical"],
"cap at 1st/99th pct": fare.clip(lower=low, upper=high),
}
rows = []
for name, s in options.items():
rows.append({
"option": name,
"trips": len(s),
"mean": round(s.mean()),
"median": round(s.median()),
"total": round(s.sum()),
})
print(f"caps: {low:.0f} and {high:.0f}")
print(pd.DataFrame(rows).to_string(index=False))
PY
uv run compare.pyRead the table column by column:
- The median is 560 in every row. It barely notices outliers, errors included, which is exactly why it belongs in your report.
- The mean moves: 655 with the errors in, 644 with the extremes kept, 610 with them deleted. The raw file overstates the typical fare because three typos outweigh four refunds.
- The total shows the cost of deleting. Dropping 16 real trips removes KES 29,830, about 8% of the fares the service really earned. If someone asks "how much did we take this month?", the deleted version is wrong.
- Capping changes about 1% of rows at each end, including lifting the cheapest fares to 240, so the total is no longer what customers paid. Use it for models and averages that must resist extremes, never for money totals.
Check it worked
The caps are 240 and 1932. The table shows 600 trips and a mean of 655 for the raw file, 593 trips and a mean of 644 when you keep the extremes, 577 trips and a mean of 610 when you delete them, and 593 trips and a mean of 641 when you cap them. The median column reads 560 in all four rows.
Step 7 · Report the result with the median beside the mean
When real extremes stay in, say so, and give the reader both centres plus the spread and the count. Then nobody has to guess what a single average is hiding. Write report.py, which saves a short Markdown summary:
cat > report.py <<'PY'
import pandas as pd
df = pd.read_csv("fares_labelled.csv")
errors = df[df["status"] == "error"]
kept = df[df["status"] != "error"]
fare = kept["fare_kes"]
q1, q3 = fare.quantile([0.25, 0.75])
extremes = int((kept["status"] == "real extreme").sum())
lines = [
"# Fares per trip",
"",
f"- Trips analysed: {len(kept)} of {len(df)}",
f"- Median fare: KES {fare.median():.0f} (middle half KES {q1:.0f} to {q3:.0f})",
f"- Mean fare: KES {fare.mean():.0f}",
f"- Kept {extremes} real extreme fares (airport runs and surge pricing);"
" they pull the mean above the median.",
f"- Left out {len(errors)} records that break the fare rules"
" (listed in fare_errors.csv, sent back for checking).",
]
text = "\n".join(lines) + "\n"
with open("report.md", "w", encoding="utf-8") as f:
f.write(text)
print(text, end="")
PY
uv run report.pyEvery figure in the report is computed from the files, so if the data owner corrects the seven errors and you re-run the scripts, the report updates with them. Keep the scripts in the order you ran them: label.py before compare.py and report.py, because both read fares_labelled.csv.
When you finish, delete the practice folder with rm -r ~/outliers-demo. Check the path first: it removes everything inside it.
Check it worked
report.md exists and says 593 of 600 trips were analysed, a median of KES 560 with the middle half between 420 and 780, a mean of KES 644, 16 real extremes kept and 7 records left out.
Next steps
- See why the median and the IQR hold up where the mean and standard deviation do not in describe data with summary statistics.
- Gaps need the same care as outliers. Read handle missing data without distorting results.
- Turn the domain rules into checks that run before every analysis with validate data with pandera before analysis.
- Make the box plot clearer, or try a log scale, in plot data with matplotlib.
Related tutorials
- Describe data with summary statistics that tell the truthYou will summarise 1,200 generated household incomes with the mean, median, mode, standard deviation, IQR and percentiles, see why the mean misleads on skewed data, compare two districts and write up a figure that carries its spread and count.
- Handle missing data without distorting your resultsYou will measure where a survey's gaps are, compare dropping rows, mean, median, group-wise and time-series fills by how far each moves the averages, add missing-value flags and write down the choice you made.
- Plot data with matplotlib's figure and axes interfaceYou will draw line, bar, scatter and histogram charts with matplotlib's figure and axes interface, format their ticks as thousands, percentages and dates, annotate the busiest day, combine all four in one grid and save it as SVG and as a sharp 2x PNG.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials