An outlier is an observation that differs substantially from other observations in a sample. There are many references available about identifying outliers, whether to make adjustments for outliers, and if so, what adjustments to make. This guide does not make any recommendations on these topics. Instead, the focus is on how to perform two of the most common procedures:
trimming: removing outliers from the dataset, and
winsorization: replacing outliers with a more central value,
using tools available in SciPy, with an emphasis on transitioning from use of legacy functions to the preferred approach.
Motivation
In the past, SciPy has offered several “convenience functions” that combine trimming with computation of a statistic. Consider, for instance, scipy.stats.trim_mean.
import
os
os
.
environ
[
'SCIPY_ARRAY_API'
]
=
'1'
import
numpy
as
np
from
scipy
import
stats
np
.
set_printoptions
(
linewidth
=
120
)
x
=
np
.
arange
(
20.
)
stats
.
trim_mean
(
x
,
proportiontocut
=
0.1
)
np.float64(9.5)
Without carefully reading the documentation, it is not immediately obvious how the operation was performed: does proportiontocut refer to the proportion to cut from each tail, or is it the total proportion of the data to remove?
Likewise, when the proportion multiplied by the number of elements would not result in an integer, is the number to remove rounded up or down?
What if instead of removing a proportion, we want to remove data below and above specified thresholds. It turns out that we cannot achieve this with trim_mean; we would need to use tmean or (the similarly-named, but curiously relegated to a separate namespace) scipy.stats.mstats.trimmed_mean, instead.
What if we want to remove data outside a “confidence interval” estimate. Do any of these functions offer anything to facilitate that? No, not really.
One could take the mean after using one of the seven functions for trimming data. But which one(s) will do what we need?
So at the time of writing, SciPy offers at least half a dozen ways of taking a trimmed mean, but deciding which to use requires a lot of research, and none are able to perform all variations of the trimmed mean that we might reasonably expect them.
What about other statistics - should we use scipy.stats.tvar, scipy.stats.mstats.tvar, or scipy.stats.mstats.trimmed_var to compute the trimmed variance? If there are three functions for that and three for the mean, surely there is at least one function for computing the trimmed skewness? (Nope!)
In the spirit of the Zen of Python, we suggest the new “one– and preferably only one –obvious way” to calculate the trimmed version of many statistics: manually, in two or three lines of code, using more familiar, general-purpose features of NumPy and SciPy. Whether calculating a trimmed or winsorized statistic, there will be three steps:
Identify the outlier threshold.
Trim or winsorize.
Compute the statistic.
Identifying the threshold
SciPy now offers a quantile function with several methods useful for identifying thresholds beyond which data are to be trimmed or winsorized. The most common thresholds are those corresponding with a certain percentage of the data in each tail. To set the threshold at p=10% of the data in each tail, rounding the number of points to trim down:
Rounding the number of points to trim to the nearest integer:
stats.quantile(x,[p,1-p],method='round_nearest')
array([ 2., 19.])
Note that these methods are all subtly different from estimating the 10th and 90th percentiles of the data, which might be called for in different circumstances. Using the default method:
stats.quantile(x,[p,1-p])
array([ 2.1, 18.9])
The Harrell-Davis method:
stats.quantile(x,[p,1-p],method='harrell-davis')
array([ 1.69917358, 19.30082642])
Note that quantile is fully vectorized. Suppose we have two rows of data, and we wish to set different thresholds for each row.
x2d=np.stack([x,x])p2d=[[p,1-p],# thresholds for zeroth row[2*p,1-2*p]]# thresholds for next rowstats.quantile
Missing data
When there are missing or ignorable values but omitting them would lead to a ragged array, the two historical options have been to:
cover the missing/ignorable values with the “mask” of a NumPy masked array and use stats.mstats functions for analysis, or
replace missing/ignorable values with NaNs and use stats functions with nan_policy='omit' for analysis.
The downsides of these approaches are documented elsewhere; here, we recommend using an MArray with stats functions.
frommarrayimportnumpyas
Trimming and winsorizing
Winsorizing is cliping
Once a numerical threshold has been identified, winsorizing is simply an application of a fundamental data operation: clip.
Suppose we have n=22 observations and we wish to winsorize p=10% from each side of the data. Rounding down with method='round_outward', we would expect to winsorize ⌊pn⌋=2 points on each side. In this case, quantile returns the third data point from the left (at index 2) as the lower limit. cliping to this limit will winsorize the two lower observations, leaving the third observation unchanged. The story is similar on the right.
When extracting the low and high thresholds from the result of quantile, just remember that their positions correspond with the positions of values in the p argument.
Like winsorization, trimming is also a straightforward application of fundamental array operations.
For 1-D data, trimming is just indexing with a boolean mask that selects data to be retained.
As in the 1-D winsorization example above, suppose we want to trim two points on either side. low is the third observation from the left - the first we want to keep. Therefore, we’ll form a boolean mask with non-strict inequalities to select the data to be kept.
When the data is winsorized or trimmed data has actually been removed, working with it is no different than any other data.
np.mean(x_trimmed)
np.float64(10.5)
np.mean(x_winsorized)# result happens to be identical *for this data*
np.float64(10.5)
np.mean(x2d_winsorized,axis=-1)# results happen to be identical *for this data*
array([10.5, 10.5])
When the trimmed values are represented as masked elements of a masked array, only slightly more care is needed. For simple statistics like mean and var, use the corresponding function of the MArray namespace, mxp, rather than the NumPy namespace.
stats.mstats.trimr is also a convenience function that trims a specified proportion of the total number of elements from each tail. inclusive has no effect when the product of the proportion and the total number of elements is integral.
In 2-D, this approach of retaining only certain data may be possible if the number of elements retained in each row happen to be identical. There is one complication: boolean indexing results in a 1-D array:
When the number of elements retained in each row are identical (and only then), it is safe to reshape the output to an array with the original number of rows.
x2d[mask].reshape(x2d.shape[0],-1)# -1 means "infer from the number of elements"
The more general option is to keep the trimmed elements in their original locations but to mask them.
Note that the mask of elements to remove is the logical NOT of the elements to be kept. Since we used non-strict inequalities to retain elements, we use strict inequalities to trim them.
According to the documentation, inclusive=(True,True) means that the number of elements “masked” on each side should be rounded. In our case, p*len(x)=1.9, so we would round to 2 on each side for a total of four.
What about inclusive=(False,False)? According to the documentation, the number of elements “masked” should be truncated. In our case, p*len(x)=1.9, so we would truncate to 1 on each side for a total of two. This should give us the same result as the round_outward calculation just above.
Tuple of (lower flag, upper flag), indicating whether values exactly equal to the lower (upper) limit are allowed.
What does allowed mean? Are values equal to the limits included in the data that is trimmed or retained? Apparently, since only one point has been masked on each side, it refers to elements being retained.
Generating and applying the mask manually is much more explicit. It also tends to be more concise.
mxp.asarray(x,mask=(x<low)|(x>high))# mask values *strictly* less than 1; also mask values *strictly* greater than 18
The documentation for inclusive states that it is a:
Tuple of flags indicating whether the number of data being masked on the left (right) end should be truncated (True) or rounded (False) to integers.
Suppose we have n=19 and the proportion to mask is p=0.1. In that case, pn=1.9. With inclusive=(False,False), we round the number of elements to be masked to 2.
Minor generalizations would be needed to support axis other than -1, different left and right values of inclusive, and the inplace argument.
Results may be different when NaNs are present and nan_policy='omit'. This is because stats.mstats.winsorize is incorrect. If we have two NaNs to be omitted, we would have 17 elements left, so np=1.7, and inclusive=(False,False) would round this number up to 2. This means that two of the values on each side would be replaced with the next more central element.