Skip to content

Instantly share code, notes, and snippets.

@ogun
Created September 3, 2017 16:04
Show Gist options
  • Save ogun/9f39d79276878601dc1c787be7992f0d to your computer and use it in GitHub Desktop.
Save ogun/9f39d79276878601dc1c787be7992f0d to your computer and use it in GitHub Desktop.
A Python function to filter a list of values for outliers by using an interquartile filter
import math
def filter_outliers(values: list) -> list:
array_length = len(values)
if array_length < 4:
return values
values.sort()
if (array_length % 4) == 0:
quarter = int(array_length / 4)
q1 = (1 / 2) * (values[quarter] + values[quarter + 1])
q3 = (1 / 2) * (values[quarter * 3] + values[(quarter * 3) + 1])
else:
q1 = values[math.floor(array_length / 4 + 1)]
q3 = values[math.ceil(array_length * (3 / 4) + 1)]
iqr = q3 - q1
max_value = q3 + iqr * 1.5
min_value = q1 - iqr * 1.5
return list(x for x in values if max_value >= x >= min_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment