Articles · before 2018

A Simple Way to Find Outliers in an array with Python

Using a basic definition of an outlier we can write a simple Python function to detect such values and highlight them on a plot.

Archived article, first published before 2018. Kept as it was written; some tools and versions have moved on since.

In statistics, an outlier is an observation point that is distant from other observations. An outlier may be due to variability in the measurement or it may indicate experimental error.

The outlier definition is somewhat vague and subjective, so it's helpful to have a rule to help in considering if a data point truly is an outlier. One rule that is very simple to apply utilizes the interquartile range (or IQR): IQR=Q3−Q1, where Q1, Q3 - the lower and upper quartiles.

The rule of thumb is to define as a suspected outlier any data point outside the interval [Q1−1.5⋅IQR,Q3+1.5⋅IQR].

find_outliers.py
# Find potential outliers in values array
# and visualize them on a plot

def is_outlier(value, p25, p75):
    """Check if value is an outlier
    """
    lower = p25 - 1.5 * (p75 - p25)
    upper = p75 + 1.5 * (p75 - p25)
    return value <= lower or value >= upper


def get_indices_of_outliers(values):
    """Get outlier indices (if any)
    """
    p25 = np.percentile(values, 25)
    p75 = np.percentile(values, 75)

    indices_of_outliers = []
    for ind, value in enumerate(values):
        if is_outlier(value, p25, p75):
            indices_of_outliers.append(ind)
    return indices_of_outliers


indices_of_outliers = get_indices_of_outliers(dist)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dist, 'b-', label='distances')
ax.plot(
    indices_of_outliers,
    values[indices_of_outliers],
    'ro',
    markersize = 7,
    label='outliers')
ax.legend(loc='best')

Read More

  1. Introduction of Clementine and Data Mining. Chapter 5: Outliers and Anomalous Data.
  2. Outlier detection, Irad Ben-Gal in Maimon O. and Rockach L. (Eds.) Data Mining and Knowledge Discovery Handbook: A Complete Guide for Practitioners and Researchers," Kluwer Academic Publishers, 2005, ISBN 0-387-24435-2.
  3. Lecture Notes for Chapter 10 from Introduction to Data Mining by Tan, Steinbach, Kumar.