Skip to main content
v2026.11,986 entries · CC-BY 4.0

Outlier Detection in Python: Methods, Workflows, and Code

Learn how to detect outliers in Python using SciPy and scikit-learn with Z-scores, IQR fences, Isolation Forests, and Local Outlier Factor diagnostics.

Written and maintained by CASRAI Editorial Board

Published

On this page

Outlier detection in Python is the process of identifying observations that deviate significantly from the underlying structure of a dataset using statistical hypothesis tests, distance metrics, and unsupervised machine learning algorithms implemented in packages such as SciPy and scikit-learn. Researchers execute outlier detection workflows to prevent biased parameter estimates, identify experimental errors, and prepare clean data matrices for statistical analysis.

What Python outlier detection libraries are used for in research

In research workflows, outlier detection serves two distinct methodological purposes: data cleaning and novelty discovery. As part of systematic data cleaning steps, screening aberrant measurements prevents sensor errors and transcription artifacts from distorting ordinary least squares regressions, ANOVA effect sizes, and cluster partitions. In fields such as bioinformatics and astrophysics, outliers represent primary targets of investigation, highlighting rare genetic variants or transient celestial signals.

Python provides a comprehensive ecosystem for managing univariate and high-dimensional detection. The scientific Python stack—NumPy, SciPy, pandas, and scikit-learn—offers transparent implementations of classical dispersion metrics alongside tree-based and density-based estimators. Researchers use Python libraries to quantify anomaly scores, generate visualisations, and document inclusion decisions.

How to tell what is an outlier?

To tell what is an outlier in an empirical sample, determine whether an observation deviates from the expected distribution beyond normal sample variation, using quantitative statistical thresholds alongside domain expertise. In univariate data, analysts establish cut-offs using the standard deviation (Z-score), the interquartile range (Tukey fences), or the mean absolute deviation. A point falling beyond 3 standard deviations or 1.5 times the interquartile range signals a presumptive statistical outlier.

A formal assessment requires answering three diagnostic questions:

  • Is the value physically impossible? Negative biological ages, blood pressures of zero in living patients, or percentages outside 0 to 100 represent clear measurement errors that require removal.
  • Does the value stem from an extraneous population? Contamination can arise from non-protocol conditions, such as an ill subject or an expired reagent. When documented, such observations are legitimately excised.
  • Is the observation an authentic extreme of heavy-tailed variability? In log-normal or Pareto distributions, extreme values are natural and valid. Truncating authentic extremes artificially deflates sample variance and biases inferences.

When extreme values represent authentic observations, researchers evaluate robust methods such as winsorizing vs trimming outlier handling rather than arbitrarily deleting data points from the analysis.

What is the difference between an outlier and an anomaly?

The difference between an outlier and an anomaly lies in the data-generating process: an outlier is a statistical observation that deviates quantitatively from the remaining data points within a single distribution, whereas an anomaly is an observation generated by an entirely distinct underlying process or system state. All anomalies manifest as outliers when projected onto nominal feature distributions, but not all outliers represent true anomalies.

For example, a reaction time of 1,200 ms when the sample mean is 550 ms is an outlier in the distribution tail. In contrast, a recorded time of 12 ms is an anomaly caused by an equipment glitch or anticipatory press, stemming from a different physical mechanism.

In research software design, outlier detection algorithms operate in an unsupervised context where the training dataset contains an unknown proportion of polluting points that the model must ignore. Novelty detection algorithms, by contrast, train on clean data reflecting the nominal operating state to flag new instances as novelties or system anomalies.

How to install or access Python outlier detection tools

Python outlier detection tools are distributed through PyPI and conda-forge. To ensure numerical stability and reproducible dependency management in scientific computing, install the core libraries within an isolated virtual environment using Python 3.10 or newer.

Install the foundational scientific Python stack—NumPy, SciPy, pandas, and scikit-learn—using pip:

pip install --upgrade numpy scipy pandas scikit-learn matplotlib seaborn

For environments managed through Conda or Mamba, install the packages from conda-forge to ensure optimized linear algebra backends (such as OpenBLAS or Intel MKL):

conda install -c conda-forge numpy scipy pandas scikit-learn matplotlib seaborn

For specialized anomaly detection algorithms beyond scikit-learn—such as Copula-based Outlier Detection (COPOD) or Empirical Cumulative Distribution Functions (ECOD)—install the Python Outlier Detection (PyOD) package:

pip install pyod

Verify your installation and inspect package versions directly in a Python interactive session:

import numpy as np
import scipy as sp
import sklearn
print("NumPy:", np.__version__)
print("SciPy:", sp.__version__)
print("scikit-learn:", sklearn.__version__)

How to detect outliers in Python step by step

Executing outlier detection in research datasets requires a systematic five-step workflow transitioning from univariate visual inspection to robust parametric testing and multivariate machine learning models.

  1. Inspect univariate distributions graphically: Plot continuous variables using box plots and kernel density estimates to evaluate skewness and tail weight before applying mathematical filters.
  2. Apply parametric and robust univariate filters: Compute standard Z-scores for approximately normal variables and Median Absolute Deviation (MAD) modified Z-scores for skewed measurements.
  3. Calculate non-parametric Tukey interquartile fences: Determine Q₁, Q₃, and the interquartile range (IQR) to flag observations falling beyond inner fences (1.5 × IQR) and outer fences (3.0 × IQR).
  4. Train multivariate isolation models: Fit an Isolation Forest or Local Outlier Factor model on standardized continuous features to detect points that deviate across multi-dimensional feature interactions.
  5. Synthesize diagnostic flags and document decisions: Cross-tabulate univariate and multivariate flags to evaluate whether candidate outliers are measurement errors, localized anomalies, or legitimate extreme observations.

Which plot is best for detecting outliers?

The best plot for detecting outliers depends on data dimensionality: for univariate distributions, the box plot is the single best diagnostic plot, whereas for bivariate relationships, the scatter plot paired with residual diagnostics is optimal.

Researchers select graphical tools based on the following criteria:

  • Box Plot (Tukey Boxplot): Best for univariate screening. As documented in Section 1.3.5.17 of the NIST/SEMATECH e-Handbook of Statistical Methods, the box plot displays the median, the interquartile range (the central 50% box), and whiskers extending to the most extreme data points within 1.5 × IQR of the quartiles. Any point plotted beyond the whiskers is an individual candidate outlier.
  • Normal Probability Plot (Q-Q Plot): Best for evaluating normality assumptions. Deviations from the diagonal line in extreme tails indicate whether outliers reflect isolated anomalies or general heavy-tailed distributions.
  • Bivariate Scatter Plot: Best for two continuous variables, revealing points that follow nominal univariate distributions but violate joint covariance structures.
  • Residuals vs. Fitted Plot: Best for regression models. Points with standardized residuals exceeding ±3 or high Cook’s distance indicate disproportionate leverage on fitted model parameters.

To construct a side-by-side box plot and Q-Q plot in Python using matplotlib and SciPy, execute the following script:

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats

np.random.seed(42)
data = np.concatenate([np.random.normal(loc=50, scale=10, size=200), [95, 102, 5]])

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].boxplot(data, vert=True, patch_artist=True)
axes[0].set_title("Tukey Box Plot with Outliers")
axes[0].set_ylabel("Observed Value")

stats.probplot(data, dist="norm", plot=axes[1])
axes[1].set_title("Normal Q-Q Plot")
plt.tight_layout()
plt.close(fig)

How does the 3-sigma rule detect outliers?

The 3-sigma rule detects outliers by calculating the standardized distance of each data point from the sample mean in units of standard deviation, flagging any observation whose absolute Z-score exceeds 3 as an outlier. Under a theoretical Gaussian distribution, 68.27% of observations fall within μ ± 1σ, 95.45% within μ ± 2σ, and 99.73% within μ ± 3σ. Consequently, only 0.27% of observations (1 in 370) fall outside ±3σ by chance.

To calculate Z-scores in Python, researchers use the scipy.stats.zscore function or standard pandas operations:

import numpy as np
from scipy import stats

x = np.array([12.1, 12.4, 11.9, 12.2, 12.0, 12.3, 12.1, 45.0])
z_scores = stats.zscore(x, ddof=1)
outliers_3sigma = np.abs(z_scores) > 3.0
print("Z-scores:", np.round(z_scores, 2))
print("Outlier mask (3-sigma):", outliers_3sigma)

While straightforward, the 3-sigma rule suffers from masking: sample mean and standard deviation have a breakdown point of 0%. A single extreme value inflates the standard deviation denominator, artificially reducing the computed Z-scores of other outliers and masking their presence. For rigorous scientific applications, review the normalize Z score framework and implement the robust Median Absolute Deviation (MAD) alternative.

Worked Python example: IQR fences, robust MAD, and Isolation Forest

The following self-contained Python script demonstrates three complementary outlier detection paradigms on an empirical dataset: the non-parametric IQR rule, the robust MAD modified Z-score, and the multivariate Isolation Forest algorithm.

import numpy as np
import pandas as pd
from scipy import stats
from sklearn.ensemble import IsolationForest

np.random.seed(101)
n_samples = 100
feature_1 = np.random.normal(loc=25.0, scale=3.0, size=n_samples)
feature_2 = np.random.normal(loc=100.0, scale=15.0, size=n_samples)
feature_1[0] = 55.0
feature_2[1] = 20.0
feature_1[2] = 32.0; feature_2[2] = 145.0

df = pd.DataFrame({"measurement_a": feature_1, "measurement_b": feature_2})

q1 = df["measurement_a"].quantile(0.25)
q3 = df["measurement_a"].quantile(0.75)
iqr = q3 - q1
iqr_lower = q1 - 1.5 * iqr
iqr_upper = q3 + 1.5 * iqr
df["outlier_iqr"] = (df["measurement_a"]  iqr_upper)

med_a = df["measurement_a"].median()
mad_a = stats.median_abs_deviation(df["measurement_a"], scale="normal")
df["mod_z_a"] = 0.6745 * (df["measurement_a"] - med_a) / (mad_a / 1.4826)
df["outlier_mad"] = df["mod_z_a"].abs() > 3.5

iso = IsolationForest(n_estimators=100, contamination=0.03, random_state=42)
X = df[["measurement_a", "measurement_b"]]
df["iso_pred"] = iso.fit_predict(X)
df["iso_score"] = iso.decision_function(X)
df["outlier_iso"] = df["iso_pred"] == -1

flagged = df[df[["outlier_iqr", "outlier_mad", "outlier_iso"]].any(axis=1)]
print("Flagged outlier rows:")
print(flagged[["measurement_a", "measurement_b", "outlier_iqr", "outlier_mad", "outlier_iso"]].head())

How to read the output

Interpreting output from Python outlier detection tools requires understanding the specific numerical scales utilized by SciPy and scikit-learn.

When evaluating scikit-learn anomaly detection models such as IsolationForest and LocalOutlierFactor, read the primary outputs according to the following conventions:

  • Prediction array (predict(X)): Returns an integer vector containing +1 for inliers and -1 for outliers based on the threshold from the contamination parameter.
  • Decision function (decision_function(X)): In IsolationForest, this method returns the mean anomaly score. Negative values correspond to outliers, while positive values denote inliers. Lower scores indicate samples with shorter average tree path lengths that were isolated rapidly.
  • Negative Outlier Factor (negative_outlier_factor_): In LocalOutlierFactor, this attribute stores the opposite of the local outlier factor. Inliers have scores near -1.0, whereas severe outliers possess large negative values (such as -15.0 or -50.0), indicating local reachability density far lower than neighboring points.

When interpreting univariate statistics from SciPy, evaluate standard and modified Z-scores:

  • Z-Score (scipy.stats.zscore): Expressed in standard deviations from the sample mean. Values exceeding |Z| > 3.0 are standard screening candidates. In large samples, a normal distribution naturally contains points with |Z| > 3.0 without representing errors.
  • Modified Z-Score (MAD): Based on median absolute deviation. Boris Iglewicz and David Hoaglin established a recommended threshold of |M_i| > 3.5 for declaring an outlier. Because the median and MAD possess a 50% breakdown point, these scores remain reliable even when up to half the sample is contaminated.

For advanced multivariate clustering workflows, refer to the cluster analysis in Python guide to understand how density-based algorithms such as DBSCAN treat noise points (labeled -1) as structural outliers.

Troubleshooting Python outlier detection

Applying outlier detection tools to complex research datasets often produces diagnostic failure modes. Troubleshoot common computational and methodological issues using the solutions below.

Masking and swamping in Z-score screening

Issue: Obvious cluster anomalies fail to achieve Z-scores greater than 3 (masking), or legitimate data points are erroneously flagged when one massive outlier shifts the sample mean (swamping).

Solution: Replace standard sample Z-scores with the Median Absolute Deviation (MAD) modified Z-score or Tukey IQR fences. Because sample mean and sample variance have a breakdown point of 0%, a single extreme value artificially expands the denominator in (x - mean) / std. Use scipy.stats.median_abs_deviation(x, scale="normal") to ensure 50% breakdown resistance.

Contamination parameter setting errors in scikit-learn

Issue: The model flags an unrealistic number of data points or returns inconsistent labels across runs.

Solution: In scikit-learn, the contamination parameter specifies the exact expected proportion of outliers in the dataset, accepting a float in (0, 0.5] or the default "auto". When set to a float such as 0.05, the model forces exactly 5% of all samples to receive the -1 outlier label. To inspect raw anomaly scores without imposing an arbitrary cut-off, retain contamination="auto" and analyze decision_function(X) directly.

Curse of dimensionality in distance-based algorithms

Issue: Distance-based estimators such as Local Outlier Factor (LOF) flag nearly all points as outliers in high-dimensional datasets (p > 50).

Solution: As dimensionality grows, pairwise Euclidean distances become equidistant, degrading density estimates. Prepend dimensionality reduction—such as Principal Component Analysis (PCA)—prior to computing LOF, or deploy tree-based ensemble estimators such as IsolationForest.

Memory errors and execution bottlenecks with large samples

Issue: Running LocalOutlierFactor on datasets exceeding 50,000 samples exhausts memory.

Solution: Standard LOF constructs a pairwise distance matrix with O(n²) complexity. For large samples, use IsolationForest(n_estimators=100, max_samples=256), which achieves O(n log n) complexity by sub-sampling partitions.

Handling missing values during fitting

Issue: SciPy and scikit-learn estimators raise ValueError: Input contains NaN, infinity or a value too large.

Solution: SciPy functions accept nan_policy="omit" to ignore missing values. In scikit-learn, impute continuous missing features using sklearn.impute.SimpleImputer(strategy="median") prior to model fitting.

Free alternatives to Python for outlier detection

While Python provides a flexible programming environment for algorithmic outlier detection, research teams frequently evaluate open-source and specialized statistical software suites based on reproducibility requirements and graphical interface needs. The comparison table below evaluates primary alternatives.

Software Tool License and Cost Primary Interface Key Detection Methods Best Research Use Case
R (stats, robustbase, isotree) Open Source (GPL) Command Line / RStudio Tukey fences, Grubbs test, Rousseeuw MCD, Isolation Forests via isotree Biostatistics, academic publishing, and comprehensive graphical diagnostic workflows.
Julia (OutlierDetection.jl) Open Source (MIT) Command Line / REPL kNN, LOF, Isolation Forest, Copula models, unified composable API High-performance scientific computing and large-scale streaming time-series anomaly detection.
KNIME Analytics Platform Open Source (GPLv3 core) Visual Node Workflow Numeric Outliers node (IQR), Rule Engine, integrated scikit-learn bridge Translational laboratory pipelines and clinical researchers requiring code-free visual workflows.
Orange Data Mining Open Source (GPLv3) Visual Interactive Canvas Outliers widget (One-Class SVM, Isolation Forest, Elliptic Envelope, LOF) Exploratory data analysis, graduate teaching, and rapid visual clustering diagnostics.
JASP Open Source (GPLv3) Graphical Menu / Spreadsheet Box plots with labeled outliers, Mahalanobis distance, Cook’s distance Psychological research and transparent Bayesian/frequentist hypothesis testing.

The data table below compares the statistical assumptions, breakdown points, and computational characteristics of the six primary outlier detection methodologies implemented across the Python scientific stack.

Frequently asked questions

How to tell what is an outlier?

To tell what is an outlier, evaluate whether an observation deviates from the expected distribution of the sample using established statistical criteria: a Z-score greater than 3, a value beyond 1.5 times the interquartile range (IQR) on a box plot, or an Isolation Forest anomaly score below zero. Confirm that the observation is not an authentic extreme value of a heavy-tailed population before taking corrective action.

Which plot is best for detecting outliers?

The box plot (Tukey boxplot) is the best plot for detecting univariate outliers because it directly plots individual data points falling beyond the 1.5 × IQR whiskers. For bivariate and regression relationships, scatter plots and residual vs. fitted plots are optimal for detecting structural leverage points.

What is the difference between an outlier and an anomaly?

An outlier is an empirical data point that deviates quantitatively from the remaining values within a given distribution. An anomaly is an observation generated by an entirely different physical process, defect, or system state. While anomalies manifest statistically as outliers, many natural outliers represent valid extreme values of nominal heavy-tailed processes.

How does the 3-sigma rule detect outliers?

The 3-sigma rule detects outliers by standardizing observations into Z-scores and flagging values with |Z| > 3. In normal data, 99.73% of values fall within 3 standard deviations of the mean. Values beyond this threshold have less than 0.27% probability of occurring by chance. In contaminated samples, use MAD to prevent extreme values from distorting the standard deviation.

What is the difference between ddof=0 and ddof=1 in SciPy zscore?

In scipy.stats.zscore, the ddof parameter specifies the delta degrees of freedom used to calculate the standard deviation divisor. The default ddof=0 computes the population standard deviation using divisor N, while ddof=1 computes the unbiased sample standard deviation using divisor N – 1. In academic research samples, set ddof=1 to align with standard statistical reporting.

Should researchers delete outliers from their datasets?

Researchers should not automatically delete outliers. Documented physical measurement errors or protocol violations should be removed or corrected. For legitimate extreme observations, retain the data and report sensitivity analyses comparing models with and without the points, or adopt robust estimators such as Huber regression, trimmed means, or winsorization.

Sources

Data: Outlier Detection Methods in Python

Comparative specifications, statistical foundations, breakdown points, and Python library implementations across six core outlier detection algorithms.

Period covered: 2026. Coverage: Global.

Outlier Detection Methods in Python
MethodParadigmDistribution AssumptionBreakdown Point (%)ComplexityPython Implementation
Standard Z-Score (3-Sigma)Parametric univariateNormal (Gaussian)0O(n * d)scipy.stats.zscore
Modified Z-Score (MAD)Robust univariateNone (distribution-free)50O(n log n)scipy.stats.median_abs_deviation
Tukey Interquartile FencesNon-parametric univariateNone (distribution-free)25O(n log n)numpy.percentile / pandas.DataFrame.quantile
Isolation ForestEnsemble tree partitioningNone (non-parametric multivariate)50O(t * n log s)sklearn.ensemble.IsolationForest
Local Outlier Factor (LOF)Density-based proximityNone (local density variation)50O(n^2 * d) or O(n log n * d)sklearn.neighbors.LocalOutlierFactor
Minimum Covariance DeterminantRobust elliptical covarianceMultivariate Normal50O(c * n * d + d^3)sklearn.covariance.EllipticEnvelope

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Outlier Detection in Python: Methods, Workflows, and Code

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →