Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to Treat Outliers in Python: Detect with IQR and Z-Score

How to Treat Outliers in Python: Detect with IQR and Z-Score, Then Decide What to Do

Treating outliers in Python is two separate jobs: detection and decision. Detection usually comes from the IQR (the distance between the first and third quartile) or from the z-score (how many standard deviations a value sits from the mean), while the decision — remove, cap, or keep — depends on whether the point is an error, how large your sample is, and whether the model you plan to fit reacts to extreme values.

Topics: outliers, python, estatística

What is an outlier and why does it change what your model learns?

An outlier is a value that sits far from the pattern of a column. It can be a collection error — humidity at 900%, an age of 250, an income with an extra digit — or a real, rare case that exists in the business, such as a single unusually large purchase.

The impact depends on the model. Mean and standard deviation get pulled by a handful of extreme points, and models that minimize squared error or measure distance, like linear regression, logistic regression, K-Means and SVM, inherit that distortion. Tree-based models — decision trees, Random Forest, Gradient Boosting, XGBoost and LightGBM — split on value ranges rather than distances and are usually far less bothered by extremes.

So the useful question is not "how do I delete outliers" but "does this record represent the phenomenon I want to predict?". Without that answer, any automatic cutoff is a guess dressed up as a rule.

How do you detect outliers with IQR in Pandas?

The IQR is the gap between the third quartile and the first quartile. The usual fences sit at 1.5 IQR below Q1 and 1.5 IQR above Q3. Because it is built from quartiles, the method does not assume a normal distribution and is not dragged around by the extreme values it is trying to find.

A minimal example on an income column:

{'code': "q1 = df['income'].quantile(0.25)\nq3 = df['income'].quantile(0.75)\niqr = q3 - q1\nlower = q1 - 1.5 * iqr\nupper = q3 + 1.5 * iqr\noutliers = df[(df['income'] < lower) | (df['income'] > upper)]\noutliers.shape[0]"}

How do you detect outliers with z-score in Python?

The z-score tells you how many standard deviations a value sits from the mean: z = (x - mean) / standard deviation. The common cutoff is |z| > 3; tighter values like 2 make the rule more aggressive and need a justification you can write down.

df['z_income'] = (df['income'] - df['income'].mean()) / df['income'].std() suspects = df[df['z_income'].abs() > 3]

The catch is that the mean and the standard deviation are computed with the outliers still inside the calculation. In small or heavily skewed samples, one extreme value inflates the standard deviation and can hide itself. A robust alternative compares each value against the median and the median absolute deviation (MAD); when the column is skewed — income, transaction value, session counts — the IQR is often the simpler starting point.

Looking at the distribution before choosing a rule matters more than the rule itself. A histogram or box plot on a skewed column usually explains why a cutoff flagged a third of your rows.

Should you remove, cap, or keep the outlier?

Remove the row when the value is impossible or traceable to a source error in collection, typing or integration — a height of 15 meters, a date outside the collection window. Removing also makes sense when there are very few such records and you can justify each one.

Cap (winsorize) when you replace the extreme value with a fence instead of dropping the row. This is the natural choice when the extreme is real, when many points sit on the tail, or when you do not want to lose the other columns of that record because of one field.

Keep the value when the outlier is exactly the event you are modeling — fraud, default, equipment failure — or when the model is tree-based and your validation metrics hold up with the point in place. A middle path is to keep the original value and add a binary indicator that marks the extreme case, letting the model decide how much weight to give it.

Whatever you choose, write it down: the criterion, the share of rows affected, and the validation score before and after. Outlier treatment that nobody documented is impossible to reproduce or defend later.

How do you stop outlier rules from leaking into your test set?

Detection rules that use statistics are fitted parameters, so they belong to the training set. If you compute quartiles, means or standard deviations over the full dataset and then split, information about the test rows has already shaped the boundaries — a subtle leak that makes offline scores look better than they are.

The safer order is: split first, compute Q1/Q3 or mean/std on the training rows only, then apply those same numbers to the validation and test sets. A value that falls outside the training fence in the test set is still a legitimate extreme, not something to delete.

This matters most in time-based splits, where the future distribution shifts. A fence learned on last year's data may flag normal values next quarter, which is a reason to monitor the flagged share over time rather than freeze a rule forever.

What does outlier handling look like in a real project?

In practice the work runs in a loop: describe() the column, plot it, count how many rows fall outside the fences, read a sample of those rows, and only then pick remove, cap or keep. The count is the fastest diagnostic — 2% outside the fences is a case for inspection, while 20% usually means the rule or the variable itself is wrong.

That sequence is the same one used in exploratory analysis before machine learning. The Python for Data Science and Analytics course covers data cleaning and preparation, outlier detection, NumPy and Pandas, and visualization in its core modules, then moves into regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection and cross-validation, closing with an end-to-end project that runs from exploratory analysis to a fitted model. Lessons are recorded and self-paced, with guided exercises, a completion certificate and ongoing access after purchase.

No prior programming is required to start, and the full syllabus is on python.paanalytics.net/. Enrollment runs through the Hotmart checkout, with card or boleto.

What you observeAction to considerWhy
Value impossible in the real world (age 250, humidity 900%)RemoveIt is a data error, not a rare event
A few extreme cases in a large sample, plausible in the domainCap at the IQR or percentile fenceKeeps the row's other columns while limiting its leverage
Many rows on the tail, or a skewed column such as incomeCap, or move to a rank-based or tree modelDeleting 15-20% of rows changes the population you describe
The extreme value is the event you are predicting (fraud, failure)Keep, and consider resampling or class weightsRemoving it deletes the signal you want to learn
Tree-based model with stable validation metricsKeep and re-check metricsSplits use value ranges, not distances
You want the original value preserved but the rarity signaledAdd a binary indicator columnThe model learns the weight of the flag itself

Decision criteria come from general data-analysis practice, not from measurements or benchmarks published by the course.

Learn data cleaning and outlier detection hands-on, from zero to a full machine learning project

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Is 1.5 always the right IQR multiplier?

No. It is a convention that works well for many roughly symmetric columns. Long-tailed variables often need a wider factor like 3.0, and the choice should be stated in your notes so the rule can be reproduced or challenged later.

Can I use a z-score on skewed data?

You can compute it, but the cutoff means less. The mean and standard deviation are pulled by the same extremes you are trying to detect, so the rule tends to under-flag on long tails. Compare it with the IQR or a median-based score before trusting it.

Does removing outliers always improve model accuracy?

No. Removal changes the population your model describes. If the extreme cases are part of the real world, dropping them can make offline metrics look better while the model performs worse on new data that still contains those cases. Validate before and after instead of assuming.

What about outliers in the target variable?

Treat them with more caution than features. A capped or removed target changes what the model is asked to predict, and in regression that shifts the interpretation of every coefficient. Inspect those rows individually and prefer keeping them unless they are confirmed errors.

Should tree-based models skip outlier treatment entirely?

They usually need less of it, because splits work on value ranges rather than distances. That is not the same as ignoring the column: an impossible value — a negative age, a date in the future — is still a data error and should be fixed in the source, whatever model you fit.

Ler em português →