Outlier Detection (IQR Method)
What is IQR?
Section titled “What is IQR?”The Interquartile Range (IQR) is:
- Q3 (75th percentile) − Q1 (25th percentile)
A common rule flags outliers outside:
- Lower bound = Q1 − 1.5 × IQR
- Upper bound = Q3 + 1.5 × IQR
Example
Section titled “Example”import pandas as pd
df = pd.DataFrame({"amount": [100, 110, 120, 115, 105, 130, 125, 3000]})
q1 = df["amount"].quantile(0.25)
q3 = df["amount"].quantile(0.75)
iqr = q3 - q1
lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr
print("Q1:", q1)
print("Q3:", q3)
print("IQR:", iqr)
print("Bounds:", lower, upper)
outliers = df[(df["amount"] < lower) | (df["amount"] > upper)]
print(outliers)Flag outliers (keep rows, add a column)
Section titled “Flag outliers (keep rows, add a column)”df["is_outlier"] = (df["amount"] < lower) | (df["amount"] > upper)
print(df)- IQR is robust for skewed data.
- Outlier detection is not outlier removal.
- Always validate outliers with domain context.
Visualize it
Section titled “Visualize it”flowchart LR A["Sort the values"] --> B["Compute Q1 and Q3"] B --> C["IQR = Q3 - Q1"] C --> D["Lower fence = Q1 - 1.5*IQR
Upper fence = Q3 + 1.5*IQR"] D --> E["Flag values outside the fences"]
A box plot is just this rule drawn as a picture: the box spans Q1 to Q3, the whiskers reach out to the fences, and anything past them is plotted as its own dot.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Compute Q1, Q3, and IQR
Section titled “Exercise 1 – Compute Q1, Q3, and IQR”Exercise 2 – Compute the fences
Section titled “Exercise 2 – Compute the fences”Exercise 3 – Flag the outliers
Section titled “Exercise 3 – Flag the outliers”Detection is only half the job — see Handling Outliers for what to actually do once you’ve found them.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading