Monday , November 30 2026
Detect and handle outliers in pandas with the IQR rule, z-scores and Isolation Forest, with tested outputs showing how one bad value distorts results.

Outlier Detection in Python: IQR, Z-Score and Isolation Forest

Updated: 29 November 2026Level: IntermediateReading time: about 9 minutespandas · scikit-learn · tested

An outlier is a value far from the rest of the data. Some are errors (a typo of 900000 instead of 90000); some are real and important (a fraud transaction). Detecting and handling them correctly protects your statistics and models.

What You Will Learn

  • The IQR rule
  • Z-scores
  • How outliers distort statistics
  • Remove, cap or keep?
  • Model-based detection

Prerequisites

EDA – uses emp.csv from that page.

IQR Rule

Example
import pandas as pd
df = pd.read_csv("emp.csv")
q1, q3 = df.salary.quantile([.25, .75])
iqr = q3 - q1
lo, hi = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(round(lo), round(hi))
print(df[(df.salary < lo) | (df.salary > hi)])
Output
2850 120850
   age    city  experience    salary
9   24  Mumbai          25  900000.0

Explanation: Values more than 1.5 × IQR beyond the quartiles are flagged – the same rule a box plot uses for its whiskers. Only row 9 is outside the fences. It is also impossible: 25 years of experience at age 24.

Z-Score

Example
z = (df.salary - df.salary.mean()) / df.salary.std()
print(df[z.abs() > 3].index.tolist())
Output
[9]

Explanation: A z-score counts standard deviations from the mean; |z| > 3 is a common cut-off. It assumes roughly normal data, and the outlier itself inflates the mean and std, so the IQR rule is usually more robust.

Impact of One Outlier

Example
clean = df[df.salary < hi]
print(clean.shape, round(clean.salary.mean(), 1))
print(clean[["experience", "salary"]].corr().round(2).iloc[0, 1])
Output
(196, 4) 60804.6
0.93

Explanation: Removing one bad row (and the 3 missing values, since NaN < hi is False) drops the mean from 65,064 to 60,805 and raises the experience–salary correlation from 0.37 to 0.93.

Handling Options

Option Code When
Remove df[df.salary < hi] Clear errors
Cap (winsorise) df.salary.clip(upper=hi) Real but extreme values; keep the row
Impute set to NaN, then fill with median Error in one column of a useful row
Transform np.log1p(df.salary) Naturally skewed data like income
Keep – Outliers are the signal (fraud, faults)
Example
import numpy as np
fixed = df.copy()
fixed.loc[9, "salary"] = np.nan
fixed["salary"] = fixed.salary.fillna(fixed.salary.median())
print(fixed.salary.isna().sum(), round(fixed.salary.mean(), 1))
Output
0 60804.5

Model-Based Detection

Example
from sklearn.ensemble import IsolationForest
X = df[["experience", "salary"]].dropna()
iso = IsolationForest(contamination=0.01, random_state=0).fit(X)
print(X[iso.predict(X) == -1].index.tolist())
Output
[9, 152]

Explanation: Isolation Forest finds unusual combinations across several columns and is used for fraud and anomaly detection. With 1% contamination it flags two points: row 9 (the 900,000 error) and row 152, a borderline but genuine value – a reminder to inspect flagged rows rather than delete them automatically.

Note: Always investigate before deleting. Document every outlier rule so results are reproducible.

Series

Data Science series: What is Data Science · Lifecycle · Data Cleaning · EDA · Outliers · Feature Engineering · Visualization · Seaborn · Roadmap

Interview Questions

Q: How does the IQR rule work?
Flag values below Q1 − 1.5·IQR or above Q3 + 1.5·IQR.

Q: Why can z-scores miss outliers?
Outliers inflate the mean and standard deviation, and the method assumes normality.

Q: Should you always remove outliers?
No – remove errors, but keep or model real extreme values, especially in fraud or anomaly problems.

Practice Exercises

  1. Apply the IQR rule to every numeric column of a dataset with a loop.
  2. Compare a linear regression trained with and without the outlier.

Summary

Use the IQR rule or z-scores to flag outliers, investigate them, then remove, cap, impute, transform or keep them. One bad value can change the mean and hide real relationships.

Next: Feature Engineering

About Machine Learning

Check Also

Exploratory Data Analysis (EDA) in Python: Step-by-Step Checklist

A step-by-step EDA checklist in pandas with tested outputs: shape, missing values, describe, value counts, groupby, correlations and charts.