Outlier detection in Python is less about picking a clever algorithm than about knowing what you are looking for. A value can be unusual and correct, or ordinary-looking and wrong. This guide tests three common methods, the IQR rule, the z-score and Isolation Forest, on a dataset where some rows are provably impossible, so we can count what each method finds.
The data is the diamonds table from the seaborn sample data: 53,940 diamonds with carat, price and the physical size x, y and z in millimetres. Code was run with pandas 3.0.5 and scikit-learn 1.9.1. There are no missing values, which is why the problems below are easy to miss.

Start by looking, not by detecting
import pandas as pd, numpy as np
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/diamonds.csv"
d = pd.read_csv(url)
print(d[["carat", "price", "x", "y", "z"]].describe().round(2))Output:
carat price x y z
count 53940.00 53940.00 53940.00 53940.00 53940.00
mean 0.80 3932.80 5.73 5.73 3.54
std 0.47 3989.44 1.12 1.14 0.71
min 0.20 326.00 0.00 0.00 0.00
25% 0.40 950.00 4.71 4.72 2.91
50% 0.70 2401.00 5.70 5.71 3.53
75% 1.04 5324.25 6.54 6.54 4.04
max 5.01 18823.00 10.74 58.90 31.80The summary already shows two problems. The minimum of x, y and z is 0.00, which is not a size a diamond can have, and the maximum of y is 58.90 mm and of z is 31.80 mm while the 75th percentile is only 6.54 and 4.04. Let us count them.
dims = ["x", "y", "z"]
print("rows with a zero dimension:", (d[dims] == 0).any(axis=1).sum())
print(d.sort_values("y", ascending=False).head(2)[["carat", "price", "x", "y", "z"]])
print(d.sort_values("z", ascending=False).head(1)[["carat", "price", "x", "y", "z"]])Output:
rows with a zero dimension: 20
carat price x y z
24067 2.00 12210 8.09 58.9 8.06
49189 0.51 2075 5.15 31.8 5.12
carat price x y z
48410 0.51 1970 5.12 5.15 31.8A 0.51 carat diamond is about 5 mm across, so y = 31.8 and z = 31.8 are almost certainly typing errors, and the 58.9 mm row is the same kind of mistake. I define an impossible row as one with a zero dimension, or a y or z above 15 mm. There are 20 with a zero and 3 with a huge value, 23 in total. These are our ground truth. It is my own definition, not one supplied with the data.
bad = (d[dims] == 0).any(axis=1) | (d.y > 15) | (d.z > 15)
print(bad.sum())Output:
23Method 1: the IQR rule
The IQR rule flags values more than 1.5 interquartile ranges below the first quartile or above the third. It uses medians and quartiles, so a few giant values do not move the fences.
def iqr_flag(s, k=1.5):
q1, q3 = s.quantile([0.25, 0.75])
i = q3 - q1
return (s < q1 - k * i) | (s > q3 + k * i)
iqr_any = iqr_flag(d.x) | iqr_flag(d.y) | iqr_flag(d.z)
print("flagged:", iqr_any.sum(), "| impossible rows caught:", (iqr_any & bad).sum())
print("price flagged:", iqr_flag(d.price).sum(), "| with k=3:", iqr_flag(d.price, 3).sum())Output:
flagged: 61 | impossible rows caught: 23
price flagged: 3540 | with k=3: 120On the three size columns the IQR rule flags 61 rows and catches all 23 impossible ones. On price it flags 3,540 rows (6.6%) with the default 1.5, and 120 with k = 3. Almost all of those 3,540 diamonds are real stones: they have a median carat weight of 2.0, and large stones simply cost more. The rule only knows the shape of one column, not that price follows carat.
Method 2: the z-score
def z_flag(s, t=3):
return ((s - s.mean()) / s.std()).abs() > t
z_any = z_flag(d.x) | z_flag(d.y) | z_flag(d.z)
print("flagged:", z_any.sum(), "| impossible rows caught:", (z_any & bad).sum())
print("price flagged:", z_flag(d.price).sum(), "| largest price z:", round(((d.price - d.price.mean()) / d.price.std()).max(), 1))
print("z of the 58.9 mm value:", round((58.9 - d.y.mean()) / d.y.std(), 1))Output:
flagged: 70 | impossible rows caught: 23
price flagged: 1206 | largest price z: 3.7
z of the 58.9 mm value: 46.5The z-score also catches all 23, with 70 rows flagged. The weakness is that the mean and standard deviation are themselves pulled by the outliers. Here a 58.9 mm value in 53,940 rows is so rare that the damage is small (the standard deviation of y is 1.142 with it and 1.113 without the two giant y values), but in a small dataset one huge value can inflate the standard deviation enough to hide itself. On price, z > 3 flags 1,206 rows and the largest z is only 3.7, so a price of $18,823 is a legitimate high value, not an error.
Method 3: Isolation Forest
Isolation Forest builds random trees and measures how quickly a row can be separated from the rest. Rows that are isolated in few splits get a high anomaly score. It looks at several columns together, but you must choose how many rows to flag with contamination.
from sklearn.ensemble import IsolationForest
X = d[["carat", "x", "y", "z", "price"]]
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=0).fit(X)
iso_flag = pd.Series(iso.predict(X) == -1, index=d.index)
print("flagged:", iso_flag.sum(), "| impossible rows caught:", (iso_flag & bad).sum())Output:
flagged: 540 | impossible rows caught: 11With contamination at 1%, it flags 540 rows (that is the setting at work, not a finding) and catches only 11 of the 23 impossible rows. The 540 flagged diamonds have a median weight of 2.31 carat (all diamonds: 0.70) and a median price of $16,194 (all: $2,401), so it is mostly flagging genuinely large, expensive stones. A different contamination value or a scaled input would change that, and I did not tune it, so read this as one honest default run rather than a verdict on the method.
Outlier detection in Python: what to do with flagged rows
All three methods answer “which rows are unusual”, not “which rows are wrong”. Of the 3,540 price outliers, only 9 were among the impossible rows; the other 3,531 were real, expensive diamonds. The 23 impossible rows needed a rule about what a diamond can physically be, and the simplest tools found them. A sensible order is: look at the summary, write down what values are possible, flag against that, and only then use a statistical method for the leftover judgement calls. For removing or fixing the bad rows, see how to clean and preprocess data; for a wider first look at a new table, exploratory data analysis in Python; and if you plan to model afterwards, keep any filtering inside the training split as shown in train test split in Python.
The scikit-learn reference is the outlier detection user guide. The data comes from the seaborn-data repository. Not tested here: local outlier factor, DBSCAN and robust z-scores based on the median.
FAQ
What is the best method for outlier detection in Python?
There is no single best one. In this test the IQR rule and the z-score caught all 23 impossible rows with 61 and 70 flags, while Isolation Forest with default settings caught 11 of 23 with 540 flags. The right method depends on whether your outliers are errors or rare real values.
Should I remove outliers?
Only if you can show they are errors. Rare but real values, like the 3,540 high prices here, carry information and removing them can bias a model.
Why is the IQR rule more robust than the z-score?
Quartiles ignore how extreme the largest values are, but the mean and standard deviation include them, so a few huge values can distort the z-score cutoff.
How do I choose contamination in Isolation Forest?
It is the expected share of anomalies. If you do not know it, you are guessing; check a sample of the flagged rows by hand, as we did here, before trusting the setting.
