Ir para o conteúdo

Lição 16 · Outliers and Impossible Values

Detecting and Handling Outliers

Detect outliers with the IQR rule and robust z-scores, investigate before acting, and choose to keep, correct, cap, transform or exclude unusual values.

An outlier is a value far from most of the others. It might be a typing mistake, a different unit, a rare but real event or the most important record in the file. Statistics can point at unusual values. Only investigation can say what they are.

Look first

Sort the column, view the smallest and largest values, and draw a histogram or box plot. Compare the mean with the median: the mean is pulled toward extremes, while the median moves much less.

Why the mean and standard deviation can fail

A common rule flags values more than three standard deviations from the mean. In small or contaminated data, the outlier itself inflates the standard deviation and can hide. This is called masking.

Python An outlier hides itself

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The value 500 is plainly strange, but its z-score stays below 3, so nothing is flagged.

The IQR rule

The interquartile range (IQR) is the distance between the first and third quartiles, which covers the middle half of the data. A common convention flags values below Q1 - 1.5 * IQR or above Q3 + 1.5 * IQR.

Robust z-scores

The median absolute deviation (MAD) is the median distance from the median. One common robust score is 0.6745 * (x - median) / MAD, and a cutoff of 3.5 is often suggested. If at least half the values are identical, MAD is zero and this score cannot be used.

Python IQR and MAD side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Libraries compute quartiles in different ways, so limits can differ a little between tools. The multipliers 1.5 and 3.5 are conventions, not laws.

Compare within groups

A price of 900 would be odd for a pen and normal for a laptop. Check outliers within product, region or season. In skewed data such as income or file sizes, the rules above can flag many legitimate high values. A log transform (for positive values) can make such data easier to judge.

Python pandas: flag outliers within each group

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pen priced at 90 is flagged, while laptop prices are judged against other laptops. Very small groups give unstable quartiles, so set a minimum group size.

Time series

In data over time, a value can be unusual only for its moment, such as daytime traffic levels in the middle of the night. Compare with a recent window or the same hour in previous weeks, and keep known events, such as holidays and sales, in mind.

Decide what to do

Finding Reasonable action
Confirmed entry error with a known true value Correct it and log the change
Wrong unit Convert it, if the unit is certain
Impossible, true value unknown Set to missing and flag
Real but extreme Keep, and use robust summaries
Outside the scope of the question Exclude from this analysis and say so
Unknown Flag and ask

Capping (a related method is called winsorizing) replaces extreme values with a limit. It reduces their influence, but it changes real measurements. If you use it, do it in an analysis column, keep the original and report the limits.

Report both ways

When extremes affect your conclusion, show the result with and without them. If the story changes, that fact is part of the finding.

Common mistake: removing outliers again and again until the chart looks smooth. Each pass changes the quartiles and can create new "outliers". Decide rules before you look at how they change your result.

In fraud detection, safety monitoring and quality control, outliers are often exactly what you want to find. Do not delete them there as a cleaning step.

A worked investigation

Suppose a daily sales column has one day about ten times higher than usual. Do not start with a formula. Open the rows behind that day. Is it one very large order or many normal ones? Do the order IDs repeat? Did all the rows come from one file? Was there a promotion?

If the rows are repeats from a double load, the fix belongs in your duplicate rule, and the "outlier" disappears. If it is one bulk order confirmed by the sales team, the value is correct. You keep it and perhaps describe typical days with the median. If it is a quantity typed with an extra zero and the source system confirms the right number, you correct it and log the change.

The same flag led to three different actions. The statistics only told you where to look.

Flag, do not filter

Store the result of each detection rule as a column, such as price_flag, with the name of the rule and the limits used. Then each analysis can decide whether to include flagged rows. Save the limits with the run. If you calculate them from each new batch, they move with the data, and a batch full of errors can make errors look normal. For monitoring, some teams set limits from an earlier, reviewed period instead.

More than one column

A record can be unusual only in combination: a normal height and a normal weight that make little sense together. Scatter plots reveal some of these cases. There are also multivariate and machine learning methods for detecting anomalies. They can help you find candidates, but their flags need the same investigation as any other.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Why can the three standard deviation rule miss a huge value?

    Extreme values affect the very statistics used to judge them.
  2. 2. A value is flagged by the IQR rule. What does that prove?

    A flag is a prompt to investigate, not a verdict.
  3. 3. When is the MAD-based score unusable?

    You cannot divide by zero, and MAD is zero when many values equal the median.

Summary

  • Outliers are unusual, not automatically wrong.
  • Prefer median-based and quartile rules when extremes are present.
  • Judge values within sensible groups and time windows.
  • Keep originals, record actions and report their effect.

Next: Impossible Values and Unit Errors

Seu progresso fica salvo neste navegador. Não precisa de conta.