Data Cleaning EDA Machine Learning 34 min read July 5, 2026
BY: Statistics Fundamentals Team
Reviewed By: Minsa A (Senior Statistics Editor)

Handling Outliers and Missing Data in Real Datasets

A single extreme value — a patient weight of 990 kg where the unit should have been pounds, or a purchase total of $999,999 from a data entry slip — can twist a model's predictions for every other record in the dataset. Outliers and missing values are the two most common quality problems in real data, and dealing with them badly is one of the quickest ways to turn a technically sound analysis into a misleading one.

This guide from Statistics Fundamentals covers the full workflow: how to spot each problem, which treatment to apply in each situation, and what happens when you get it wrong. Every method is shown with a worked numerical example before any formulas appear.

What You Will Learn
  • ✓ What outliers are, what causes them, and the different types
  • ✓ Every detection method from box plots to Isolation Forest
  • ✓ When to remove, cap, transform, or keep an outlier
  • ✓ The three types of missing data and why the type changes your strategy
  • ✓ Mean, median, KNN, and multiple imputation — compared with real numbers
  • ✓ Three fully worked examples: retail, healthcare, and customer analytics
  • ✓ An interactive IQR outlier calculator
  • ✓ A cheat sheet, common mistakes table, and full glossary

What Is an Outlier in Data?

Quick Answer — Handling Outliers in Data

An outlier is a data point that sits far from the rest of a dataset's values. Handling outliers means first deciding whether the extreme value reflects a real phenomenon or a data quality error, then applying the appropriate treatment: removal, capping, transformation, or retention. The right choice depends on the cause of the outlier and the goal of the analysis.

Definition — Outlier
An outlier is an observation that differs so much from other observations that it raises the question of whether it was generated by the same process as the rest of the data. Statistically, a common threshold is any value that falls more than 1.5 times the interquartile range below the first quartile or above the third quartile — but no single rule fits every dataset.

The word "outlier" is not a value judgment about whether a data point should stay or go. It describes a statistical relationship between one observation and the rest. A salary of $1.2 million in a dataset of hospital nurse salaries is almost certainly a data error. A salary of $1.2 million in a dataset of hedge fund managers is perfectly plausible. The number alone tells you nothing — context does.

That distinction matters because the treatment that makes sense for an error is different from the treatment that makes sense for a genuine extreme value. Deleting real extreme values from a fraud detection dataset, for instance, removes precisely the records you are trying to learn to identify.

Types of Outliers

TypeDescriptionTypical CauseUsual Treatment
Point outlierA single value that is extreme relative to the restData entry error, sensor spike, fraudCorrect if error; cap or remove if confirmed extreme
Contextual outlierA value that is normal globally but extreme in a specific context (e.g., 30°C in winter vs summer)Time-based or category-based shiftsAnalyze by segment before treating
Collective outlierA group of observations that are individually normal but anomalous togetherSystem failure, coordinated fraud, batch processing errorsInvestigate as a cluster; requires anomaly detection algorithms

What Causes Outliers?

Outliers come from two broad sources: mistakes in the data collection or entry process, and real but rare events in the underlying phenomenon.

Data collection errors include transcription slips (entering 550 instead of 5.50), unit mix-ups (pounds recorded where kilograms were expected), sensor malfunctions, and system import failures. These outliers should be corrected when the true value is known, and removed when it is not — because they carry no useful information about the phenomenon being studied.

Genuine extreme events include unusually high sales during a one-off promotion, a patient with a rare condition producing atypical lab results, or a network intrusion that really does look nothing like normal traffic. These outliers carry exactly the information an analyst needs, and removing them because they look different defeats the purpose of the analysis.

~30%
Of real-world datasets contain at least one outlier significant enough to affect model results
1.5×IQR
Standard threshold for flagging mild outliers in exploratory analysis
3.0×IQR
Threshold for extreme outliers that almost certainly warrant investigation
|Z| > 3
Z-score threshold most commonly used for normally distributed data

What Are Missing Values?

Definition — Missing Values
Missing values are observations where a variable has no recorded entry. They appear as blank cells, NaN (not a number) entries, NULL database records, or placeholder codes like -99. The reason a value is missing often matters more than the fact that it is missing, because the reason determines which method will best recover the lost information.

Missing data is the rule in real datasets, not the exception. A health survey might have 12% of income fields blank because respondents found the question sensitive. A retail transaction database might have no customer age for 40% of purchases because the field was only collected after a platform redesign. A sensor network might have random gaps where connectivity dropped.

The Three Types of Missing Data

Donald Rubin's 1976 taxonomy divides missing data into three mechanisms, and the mechanism determines the correct response. Most practitioners encounter some version of this classification even if they never use the formal names.

Missing TypeFormal NameMeaningExampleRecommended Approach
MCARMissing Completely At RandomThe probability of a value being missing is unrelated to any variable in the datasetA server outage drops 2% of rows from a log file at randomListwise deletion or simple imputation both work; bias is small
MARMissing At RandomThe probability of missingness depends on other observed variables, not on the missing value itselfOlder respondents are less likely to report income, but among each age group reporting is randomModel-based imputation using other observed variables is appropriate
MNARMissing Not At RandomThe probability depends on the unobserved value itselfPeople with very high incomes skip the income question specifically because their income is highSpecialized models or sensitivity analysis; simple imputation will introduce bias
⚠️
MNAR is the hardest case and the most common in practice

When people skip a question because the answer is uncomfortable, when a sensor stops reporting because a value exceeds its range, or when records are deleted because they showed a problem — all of these are MNAR. Standard imputation methods assume MAR or MCAR, so applying them to MNAR data can produce estimates that look precise but are systematically wrong. Always investigate why values are missing before choosing a method.

Why Handling Outliers and Missing Data Matters

Both problems share a common mechanism for causing harm: they distort the statistical summaries that every downstream step relies on. A mean calculated from a dataset containing a data entry error is a mean of the wrong data. A regression trained on records with systematically missing values learns patterns from a non-representative sample.

The consequences differ by analysis type, but none are minor. In descriptive statistics, outliers inflate the mean and standard deviation, making a dataset look more variable than it is. In linear regression, a single high-leverage outlier can rotate the regression line significantly, changing predicted values for all other inputs. In clustering, extreme values pull centroids away from natural groupings. In machine learning, models trained on corrupted data produce predictions that fail when deployed on clean data.

Domain knowledge is the most important input to any data cleaning decision

No statistical formula tells you whether a value of 180 in a height column represents 180 centimeters (plausible) or 180 inches (about 4.6 meters, impossible). A domain expert answering one question — "What are the physically possible values for this variable?" — often does more to clean a dataset than any automated detection algorithm.

Methods for Detecting Outliers

Every detection method trades off between sensitivity (catching real outliers) and specificity (not flagging normal values). No single method is right for every dataset, and using two or three together is standard practice in serious data analysis.

Interquartile Range (IQR) Method

The IQR method is the most widely used technique for exploratory outlier detection, and it is what box plots visualize. The interquartile range is the difference between the 75th percentile (Q3) and the 25th percentile (Q1). Any value below the lower fence or above the upper fence is flagged.

IQR Outlier Boundaries
Lower Fence = Q1 − 1.5 × IQR     Upper Fence = Q3 + 1.5 × IQR
Q1 = 25th percentile Q3 = 75th percentile IQR = Q3 − Q1 Extreme outlier: 3.0 × IQR
Worked Example — IQR Method

Monthly sales figures: [12, 15, 14, 10, 13, 98, 11, 16, 14, 12]

1

Sort the values: 10, 11, 12, 12, 13, 14, 14, 15, 16, 98

2

Find Q1 and Q3: Q1 = 12 (median of lower half), Q3 = 15 (median of upper half). IQR = 15 − 12 = 3.

3

Calculate fences: Lower fence = 12 − 1.5 × 3 = 7.5. Upper fence = 15 + 1.5 × 3 = 19.5.

4

Flag outliers: The value 98 exceeds the upper fence of 19.5, so it is flagged as an outlier. All other values fall within the fences.

✓ Result: The IQR method correctly identifies 98 as an outlier. No statistical assumption about normality is required — the method works on skewed distributions too, which is why it is preferred for exploratory analysis.

Z-Score Method

The Z-score measures how many standard deviations a value sits away from the mean. A Z-score beyond ±3 is the most common threshold for flagging outliers when data is approximately normally distributed. The Z-score guide covers the full formula and interpretation. Compute Z-scores directly with the Z-score calculator.

Z-Score
Z = (x − μ) / σ
x = observed value μ = mean of the dataset σ = standard deviation Flag if |Z| > 3
⚠️
The Z-score method has a blind spot

Because the mean and standard deviation used in the Z-score calculation are themselves influenced by outliers, extreme values can actually mask each other — a phenomenon called masking. In a dataset with several very large values, the mean shifts upward and the standard deviation widens, so each individual outlier produces a smaller Z-score than it would in a clean dataset. For datasets with many suspected outliers, the modified Z-score using the median and median absolute deviation (MAD) is more reliable.

Modified Z-Score (Median-Based)

Modified Z-Score
M = 0.6745 × (x − Median) / MAD
MAD = Median Absolute Deviation Flag if |M| > 3.5 0.6745 = consistency constant for normal distribution

Box Plot

A box plot visualizes the IQR method directly. The box spans Q1 to Q3, the median line sits inside the box, and the whiskers extend to the fences. Points beyond the whiskers are plotted individually as outlier markers. Box plots are the fastest way to visually scan a variable for outliers, particularly when comparing multiple variables at once. Create one instantly with the box plot generator.

Scatter Plot

When two variables are related, a scatter plot reveals outliers that would not be obvious from looking at each column individually. A data point can fall within normal range for both its x-value and y-value while still being a contextual outlier — sitting far from the regression line, for instance, where it would have a large residual. The regression scatter plot tool overlays the trend line, making these points visible immediately.

Histogram

A histogram shows the distribution of a single variable, and outliers often appear as isolated bars separated by a gap from the main distribution. Long tails in a histogram are a signal worth investigating. The histogram maker lets you adjust bin width to see whether suspected outlier bars represent one value or several.

Isolation Forest

Isolation Forest is a machine learning algorithm that detects outliers by measuring how few random splits are needed to isolate a single data point. Outliers, being unusual, require fewer splits to separate from the rest. The algorithm returns an anomaly score for each record, and records with the highest scores are the most likely outliers. It handles high-dimensional data (many variables) well, where IQR and Z-score applied to individual columns can miss multivariate outliers entirely. Scikit-learn's IsolationForest class implements this with a single function call.

Local Outlier Factor (LOF)

LOF compares the local density of a data point to the densities of its neighbors. A point in a sparse neighborhood is an outlier relative to its local context, even if it would not be flagged by a global threshold. LOF is particularly useful for datasets with clusters of different densities — fraud transaction data, for instance, where normal behavior clusters differ in their own density characteristics.

DBSCAN

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) assigns data points to clusters based on neighborhood density and labels any point that cannot join a cluster as noise — effectively marking it as an outlier. It finds clusters of any shape and handles genuinely multi-modal distributions better than centroid-based methods. Points labeled as noise by DBSCAN are natural candidates for outlier investigation.

MethodBest ForAssumes NormalityHandles High DimensionsWorks on Skewed Data
IQR / Box PlotSingle variable, exploratory analysisNoNo (per column)Yes
Z-ScoreNormally distributed dataYesNo (per column)Poor
Modified Z-ScoreRobust single-variable detectionNoNo (per column)Yes
Scatter PlotBivariate outliers relative to a relationshipNoNoYes
Isolation ForestMulti-variable, large datasetsNoYesYes
LOFDatasets with variable-density clustersNoModerateYes
DBSCANClustering with outlier labelingNoModerateYes

Methods for Handling Outliers

Detection tells you a value is unusual. Treatment requires deciding what to do about it. The choice depends on three things: why the outlier exists, how many there are, and what the analysis will be used for.

Remove the Outlier

Deletion is appropriate when an outlier is confirmed to be a data error and the true value cannot be recovered. It is also acceptable when a small number of extreme values would distort a model trained for a very different population — for instance, removing billionaires from a dataset before modeling middle-class retirement savings. Deletion should never be the default choice and should always be documented clearly.

Winsorization (Capping)

Winsorization replaces values below a lower percentile with that percentile value, and values above an upper percentile with that upper percentile value. Common choices are the 5th and 95th percentiles, though 1st/99th is used when only the most extreme values need treatment. The record stays in the dataset, but its influence on the mean and regression coefficients is reduced. Winsorization is preferred over deletion when outliers may be genuine but their exact magnitude is uncertain.

Worked Example — Winsorization

Income values in thousands: [28, 32, 35, 31, 29, 33, 34, 30, 28, 850]

1

Choose cap percentiles: 5th percentile = 28.45, 95th percentile = 67.25 (computed on the full dataset).

2

Cap the outlier: Replace 850 (above the 95th percentile threshold of 67.25) with 67.25. All other values are within range and unchanged.

3

Compare means: Original mean = 111 thousand. Winsorized mean = 34.7 thousand. The dataset now correctly reflects the typical income level without losing the observation entirely.

✓ Result: Winsorization preserves all ten records while reducing the undue influence of the 850 value. If the 850 were a genuine billionaire rather than a data error, Winsorization is more defensible than deletion because it acknowledges the high income without letting it distort predictions for everyone else.

Log Transformation

When a variable is right-skewed — salary, house prices, transaction amounts — a log transformation compresses the upper tail, making the distribution more symmetric and the extreme values less influential. Log transformation does not remove outliers; it changes their scale relative to the rest of the data. It cannot be applied to zero or negative values without adjustment. The standard deviation guide covers why symmetric distributions produce more reliable variance estimates.

Robust Scaling

Standard scaling divides by the standard deviation, which is sensitive to outliers. Robust scaling uses the median and IQR instead, so extreme values have little effect on the scaled result. Scikit-learn's RobustScaler applies this directly. This approach is particularly useful as preprocessing before algorithms that are sensitive to feature scale, such as SVM or KNN.

Domain-Based Decisions

Some outliers need no statistical treatment at all — only domain knowledge. A body temperature of 40.5°C is unusual but physiologically possible in a patient with a high fever, so keeping it exactly as recorded is the correct choice. An age value of 180 years is impossible, so it should be replaced with a missing value and then imputed. The statistician who says "the algorithm will handle it" without first asking "is this value plausible?" is skipping the most important step in the workflow.

Methods for Handling Missing Values

Missing value treatment ranges from simple deletion to complex probabilistic models. The appropriate method depends on the type of missingness (MCAR, MAR, MNAR), the proportion of missing values, the variable's role in the analysis, and the computational resources available.

Listwise Deletion

Listwise deletion removes any record that has at least one missing value. It is the default behavior in most statistical software. It produces unbiased estimates only when data is MCAR. When the missing proportion is small (under 5%) and the mechanism is MCAR, it is a reasonable choice. When the proportion is larger or the mechanism is MAR or MNAR, it wastes data and introduces bias.

Mean Imputation

Mean imputation replaces each missing value with the variable's mean, computed from the non-missing records. It is fast, simple, and preserves the mean of the distribution. Its drawback is that it reduces the variance — every imputed value is exactly the mean, so the distribution becomes artificially narrow, which distorts correlation estimates and makes confidence intervals too narrow.

💡
Median imputation when the distribution is skewed

If a variable has outliers that pull the mean away from the typical value, the median is a better replacement than the mean. A dataset of house prices where most values cluster around $300,000 but a handful of luxury properties push the mean to $450,000 should use median imputation — otherwise every missing price is imputed at a value that most houses in the dataset do not have.

Mode Imputation

Mode imputation replaces missing values in a categorical variable with the most frequent category. It is the natural extension of mean/median imputation to non-numeric data. Like mean imputation, it can under-represent less common categories, particularly in variables with a fairly flat distribution where no one category dominates.

KNN Imputation

KNN imputation finds the k records most similar to the record with the missing value (using other variables as the similarity measure), and fills the missing value with a weighted average (for numerical data) or majority vote (for categorical data) from those neighbors. It preserves relationships between variables better than simple imputation, at the cost of higher computation. Scikit-learn's KNNImputer implements this. The Pearson correlation guide explains the similarity measures that drive neighbor selection.

Multiple Imputation

Multiple imputation creates several complete versions of the dataset, each with different plausible imputed values drawn from a modeled distribution of the missing data. The analysis is run on each complete dataset, and the results are combined using Rubin's rules. This is the statistically preferred method when data is MAR and the proportion missing is substantial, because it correctly accounts for the uncertainty about what the missing values actually were. The statsmodels MICE implementation is widely used in Python.

Forward Fill and Backward Fill

Forward fill propagates the last observed value forward to fill subsequent missing entries. Backward fill does the opposite. Both make sense only for time series data where the assumption that a value persisted until it was next observed is defensible — stock prices or sensor readings, for example. Applying them to cross-sectional survey data would be meaningless.

Predictive Model Imputation

Predictive imputation trains a model (linear regression, random forest, or similar) on the complete records to predict the missing variable from the others, then uses the model to fill the gaps. This is effectively what MICE (Multiple Imputation by Chained Equations) does iteratively. It can capture non-linear relationships that KNN misses, and it naturally handles categorical targets. The risk is that it can produce imputed values outside the original range, which sometimes requires post-imputation capping.

MethodData TypePreserves VarianceHandles MARComputationBest When
Listwise DeletionAnyYes (on survivors)NoNoneMCAR, <5% missing
Mean ImputationNumericNo — reduces varianceNoMinimalMCAR, quick baseline
Median ImputationNumericNoNoMinimalSkewed distributions
Mode ImputationCategoricalPartlyNoMinimalLow-cardinality categories
KNN ImputationNumeric / CatBetter than meanPartiallyMediumMAR, moderate missingness
Multiple ImputationAnyYesYesHighMAR, significant missingness, research analysis
Predictive ImputationAnyYesYesMedium–HighNon-linear relationships between variables
Forward / Backward FillNumeric / CatPartlySituationalMinimalTime series with persistent states

IQR Outlier Detector Calculator

Enter your data values separated by commas to calculate Q1, Q3, IQR, and the outlier fences. Any values outside the fences are reported as outliers.

📊 IQR Outlier Detection Calculator

Enter numeric values separated by commas. The calculator reports Q1, Q3, IQR, outlier fences, and any flagged outliers.

Input Data
About This Method

The IQR method does not assume normality, making it reliable for skewed distributions. Values 1.5×IQR beyond Q1 or Q3 are mild outliers. Values 3×IQR beyond are extreme outliers and almost always worth investigating.

Q1 (25th pct)
Q3 (75th pct)
IQR
Lower Fence
Upper Fence
Outliers Found

Real Example #1: Retail Sales Dataset

A retail analyst receives a dataset of 10,000 daily store transaction records containing total_sale, quantity, customer_age, and discount_pct. Before building a sales forecasting model, the dataset needs to pass a data quality check.

VariableMissing CountMissing %Outliers DetectedAction
total_sale00%47 values > Upper fence ($2,840)Investigate — likely bulk orders; Winsorize at 99th percentile
quantity00%3 values of 9,999 (sentinel code)Replace with NaN; impute with median = 2
customer_age1,82018.2%2 values: age 5 and age 187Delete impossible values; impute remaining missing with KNN on quantity and discount_pct
discount_pct3103.1%None within business rangeMCAR (random logging gap); mean imputation acceptable
Worked Example — Retail Data Cleaning Sequence

Step-by-step cleaning decisions for the retail dataset

1

Diagnose sentinel codes in quantity: Values of 9,999 appear when a barcode scanner failed and a staff member manually keyed a placeholder. These are not real quantities. They are replaced with NaN before any imputation runs.

2

Delete impossible ages: Ages of 5 and 187 are physically impossible for a retail customer. They are removed and recorded as additional missing values before the imputation step, not after.

3

Impute customer_age with KNN: Age is correlated with purchase quantity and discount sensitivity. KNN imputation using k=5 neighbors on these two variables produces age estimates more plausible than a global median would.

4

Winsorize total_sale at the 99th percentile: Review of the 47 flagged transactions confirms they are genuine bulk orders from a corporate account, not errors. Deleting them would teach the model nothing about bulk behavior. Winsorization keeps them at $2,840 each, reducing their leverage without discarding the information.

✓ Result: The cleaned dataset retains all 10,000 records. Three distinct treatments — deletion of impossible values, KNN imputation for customer_age, and Winsorization for total_sale — were each chosen for a different reason. Using the same method for every problem would have introduced unnecessary bias.

Real Example #2: Healthcare Dataset

A hospital research team works with a patient dataset of 2,400 records containing blood_pressure_systolic, bmi, lab_glucose, and length_of_stay in days. The goal is predicting readmission risk.

VariableIssueDomain CheckTreatment
blood_pressure_systolicZ-score > 3 for 14 records (values 210–225)Hypertensive crisis threshold is 180 mmHg — values 210–225 are extreme but possible in ICURetain; flag for subgroup analysis
bmi8 records with BMI < 12 or > 70BMI below 14 is clinically incompatible with outpatient status; BMI above 60 possible but requires verificationCross-check source records; replace unverifiable extremes with NaN; impute with median by age group
lab_glucose340 missing (14.2%)Missing if no glucose test was ordered — higher in younger patients (MAR)KNN imputation using age and bmi as predictors
length_of_stay1 record: 842 daysLong-term care is possible; 842 days warrants record-level verificationVerify source — confirmed as transcription error (should be 84 days); correct directly
Verifying the source record changed the decision entirely

The 842-day length of stay would have been capped at 300 days by a naive Winsorization. Checking the original paper form revealed a transcription error — 84 was the correct value. Statistical methods can flag suspicious values, but they cannot recover from errors that are not recognized as errors in the first place. Source verification is the step that algorithmic cleaning cannot replace.

Real Example #3: Customer Analytics Dataset

An e-commerce data scientist prepares a customer dataset of 50,000 rows with lifetime_value, days_since_last_purchase, number_of_orders, and demographics for a customer segmentation model.

Worked Example — E-commerce Data Cleaning

Preparing customer data for K-means clustering

1

IQR detection on lifetime_value: Q1 = $45, Q3 = $380, IQR = $335. Upper fence (1.5×) = $882.50. 1,230 customers exceed this threshold with values up to $28,000. These are high-value customers — real and commercially important — not errors.

2

Decision: log-transform, not delete: K-means uses Euclidean distance, so a $28,000 lifetime value would overwhelm the clustering entirely. Log-transforming lifetime_value compresses the scale while keeping every customer in the analysis. After clustering, results are back-transformed for interpretation.

3

Missing demographics (32% of age field): Age is missing primarily for customers acquired through a social media channel that did not require a birthdate at signup — this is MAR (missingness predicted by acquisition channel, which is observed). Multiple imputation using acquisition channel, number_of_orders, and days_since_last_purchase produces plausible age estimates.

4

Robust scaling before clustering: Even after log-transforming lifetime_value, robust scaling (median and IQR) is applied to all features before K-means runs, ensuring no single variable dominates the distance calculation. Standard scaling would still be sensitive to any remaining extreme values.

✓ Result: The high-value customers are kept in the model — their spending patterns define one of the most commercially valuable segments. Log transformation and robust scaling handle their influence without erasing their identity, which deletion would have done.

Outliers and Missing Data in Machine Learning

The effect of data quality problems changes with the algorithm. Understanding which models are sensitive and which are robust helps prioritize cleaning effort.

AlgorithmSensitivity to OutliersSensitivity to Missing DataRecommended Treatment
Linear RegressionHigh — outliers rotate the regression lineHigh — drops records with any missing value by defaultWinsorize or remove outliers; impute missing values before training
Logistic RegressionModerate — outliers affect log-odds estimatesHigh — same as linearWinsorize extreme features; impute before training
K-Nearest NeighborsHigh — distances distorted by extreme valuesCannot operate with missing valuesRobust scaling; complete imputation required
K-Means ClusteringHigh — centroids pulled toward extremesCannot operate with missing valuesLog transform + robust scaling; impute before clustering
Support Vector MachineModerate–High — support vectors sensitive to scaleCannot operate with missing valuesRobust scaling; impute before training
Random ForestLow — tree splits based on rank, not magnitudeSome implementations handle internallyMinimal outlier treatment needed; surrogates handle some missing
XGBoost / LightGBMLow — gradient boosted trees are rank-basedXGBoost handles NaN natively via default directionOutlier treatment optional; missing values may be left as NaN
Neural NetworksHigh — large gradients from outliers destabilize trainingCannot operate with missing valuesNormalize or Winsorize inputs; complete imputation required

The simple linear regression guide shows how a single high-leverage point shifts the regression line with a concrete numerical example. The descriptive statistics outliers guide covers identification within summary statistics in more detail.

Data Cleaning Workflow

A repeatable cleaning sequence prevents the most common mistake in data preprocessing: treating each problem in isolation rather than in a defined order. The order matters because some steps alter the result of others — Winsorizing before you detect sentinel codes, for instance, can mask the sentinel's influence on the fence calculation.

1
Import and Profile

Load the data and generate summary statistics: count, mean, min, max, null count per column. This is the baseline before any changes.

2
Identify Sentinel Codes

Check for placeholder values like -1, 0, 9999, "N/A" strings stored as text, and other codes that mask missing data. Convert them to NaN before any analysis.

3
Detect Outliers

Apply IQR method and Z-score per variable. For multivariate detection, use Isolation Forest on the full feature set. Document every flagged value.

4
Investigate and Decide

For each flagged value, determine: data error, domain-plausible extreme, or genuine extreme event. Apply the appropriate treatment — delete, correct, cap, or retain.

5
Diagnose Missing Data

Tabulate missingness per column. Check whether missing values correlate with other observed variables (MAR) or appear random (MCAR). Visualize missing patterns with a heatmap.

6
Impute Missing Values

Choose the imputation method for each variable based on its missingness type, data type, and proportion missing. Apply transformations needed for downstream modeling.

Common Mistakes in Handling Outliers and Missing Data

MistakeWhy It Goes WrongWhat to Do Instead
Deleting all flagged outliers without investigation A statistical threshold is a starting point, not a verdict. Deleting real extreme values from fraud detection data removes the most useful records in the dataset. Check each flagged value against domain knowledge. Only delete confirmed errors or values with no plausible real-world explanation.
Using mean imputation on skewed variables The mean of a right-skewed distribution sits above most of the actual values. Imputing it into missing cells creates an artificial spike at a value most records do not have, distorting correlation estimates. Use median imputation for skewed distributions, or model-based imputation that accounts for the distribution's shape.
Assuming all missing data is MCAR If the probability of missingness depends on the missing value itself (MNAR), any imputation method produces biased estimates. The bias may be invisible until the model is tested on new data. Always investigate why values are missing before choosing a method. Look for patterns: which records are most likely to have the variable missing?
Imputing test data using statistics from test data Calculating mean or quartiles on the test set and using those to impute test records leaks information about the test distribution into the cleaning step — a form of data leakage that inflates measured model performance. Fit all imputation statistics (mean, Q1, Q3, KNN distances) on the training set only. Apply those fitted values to the test set.
Applying the Z-score method to non-normal data The Z-score method assumes normality. On a strongly skewed variable, values that are genuinely typical for the distribution can produce Z-scores above 3, while true outliers in the long tail produce smaller scores than expected. Use the IQR method or modified Z-score for skewed distributions. Check normality with a histogram or the bell curve generator first.
Cleaning data after splitting train and test sets If outlier removal or imputation is done on the full dataset before the train-test split, information from test records influences the cleaning of training records — another source of data leakage. Split first, then fit cleaning parameters on training data, then apply to both sets separately using the training-derived parameters.

Best Tools for Outlier Detection and Missing Data Handling

ToolOutlier DetectionMissing Data HandlingBest For
Python — PandasIQR with quantile(), describe() for quick profilingfillna(), interpolate(), dropna()Data analysts working in Python notebooks
Python — Scikit-learnIsolationForest, LOF, EllipticEnvelopeSimpleImputer, KNNImputer, IterativeImputerMachine learning pipelines requiring reproducible preprocessing
Python — SciPy / NumPyZ-score via scipy.stats.zscore, modified Z-score manuallyMasked arrays for NaN-aware operationsStatistical analysis and research computing
R — base Rboxplot.stats(), quantile(), scale() for Z-scoresna.omit(), complete.cases(), mice packageAcademic research and statistical modeling
R — mice packageN/AMultiple imputation by chained equations (MICE)Research requiring statistically valid uncertainty estimates from imputation
Excel / Power BIConditional formatting, QUARTILE function, box-and-whisker chartsIFERROR, Power Query fill operationsBusiness analysts working with smaller datasets
OpenRefineFacets and clustering to spot unusual valuesGREL transforms to fill or flag blank cellsJournalists and researchers cleaning survey or scraped data

For students working through the concepts in this guide, the Statistics Fundamentals calculator library includes a descriptive statistics calculator for quick quartile computation and a standard deviation calculator for Z-score denominators. The scikit-learn preprocessing documentation and Pandas fillna reference are the authoritative sources for implementation details.

Data Cleaning Checklist

Checklist — Outliers and Missing Data
  • Profile the dataset first: Count nulls, compute min and max, check data types. No cleaning decision should come before this baseline.
  • Convert sentinel codes to NaN: Values like -1, 0, 99999, or "N/A" stored as strings are not real missing values — they are disguised ones. Find and convert them before analysis.
  • Use the IQR method for initial outlier flagging: It requires no distributional assumption and works on skewed data. The Z-score is a useful cross-check for roughly normal variables.
  • Check each flagged outlier against domain knowledge: A statistical flag is not a reason to delete — it is a reason to investigate.
  • Determine the missingness mechanism before imputing: Is this MCAR, MAR, or MNAR? The mechanism determines which method is defensible.
  • Choose the imputation method by variable type and proportion: Median for skewed numeric, mode for categorical, KNN or multiple imputation when missingness is substantial and MAR.
  • Split train/test before fitting any cleaning parameters: Quartiles, means, and KNN neighbor models should be fit on training data only.
  • Document every decision: Which values were removed, capped, or imputed, and why. This audit trail is necessary for reproducibility and peer review.
  • Validate after cleaning: Re-run summary statistics and distributions on the cleaned dataset and compare to the original profile. Unexpected changes are a signal that something went wrong.

Outlier and Missing Data Cheat Sheet

ConceptFormula / ValueWhen to Use It
IQRIQR = Q3 − Q1All distributions; preferred for skewed data
IQR Lower FenceQ1 − 1.5 × IQRMild outlier threshold on low end
IQR Upper FenceQ3 + 1.5 × IQRMild outlier threshold on high end
Extreme Outlier FenceQ1 − 3×IQR and Q3 + 3×IQRFlags that almost certainly warrant investigation
Z-ScoreZ = (x − μ) / σ; flag if |Z| > 3Approximately normal distributions only
Modified Z-ScoreM = 0.6745×(x − Median)/MAD; flag if |M| > 3.5Robust alternative for non-normal data
Winsorization capReplace beyond kth percentile with kth percentile valueWhen outliers are real but their exact magnitude is uncertain
MCAR checkCorrelate missingness indicator with other variables; p > .05 suggests MCARBefore choosing deletion vs imputation
Mean imputationReplace NaN with mean of observed valuesMCAR, <5% missing, symmetric distribution
Median imputationReplace NaN with median of observed valuesSkewed distributions, robust to own outliers
KNN imputationReplace NaN with weighted avg of k nearest neighborsMAR, moderate missingness, relationships between variables exist
Multiple imputationm datasets, analyze each, combine with Rubin's rulesMAR, significant missingness, research requiring valid uncertainty
Log transformx' = log(x)Right-skewed variables with positive values only
Robust scaling(x − Median) / IQRFeatures for distance-based algorithms when outliers remain

Data Quality Glossary

TermDefinitionRelevance
OutlierA data point that lies far from the other values in a dataset, measured by IQR fences or Z-score thresholdsThe core subject of outlier detection and treatment
Missing ValueAn observation where a variable has no recorded entry, appearing as NaN, NULL, or blankThe core subject of imputation methods
IQRInterquartile range — the difference between the 75th and 25th percentiles; used to define outlier fencesPrimary statistic for robust outlier detection
Z-ScoreThe number of standard deviations a value sits from the mean: Z = (x − μ) / σOutlier detection under normality assumption
Modified Z-ScoreA Z-score variant using median and MAD instead of mean and standard deviation, making it robust to the outliers it is trying to detectPreferred for skewed or already-contaminated data
WinsorizationReplacing extreme values with a specified percentile value rather than removing themOutlier treatment that retains all records
ImputationThe process of replacing missing values with estimated values derived from other dataThe family of techniques for handling missing data
MCARMissing Completely At Random — the probability of missingness is unrelated to any variableThe easiest missing data mechanism; permits deletion without bias
MARMissing At Random — the probability depends on other observed variablesPermits model-based imputation using observed predictors
MNARMissing Not At Random — the probability depends on the unobserved value itselfThe hardest case; requires specialized models or sensitivity analysis
KNN ImputationReplacing missing values with a weighted average from the k most similar recordsPreserves inter-variable relationships; handles MAR well
Multiple ImputationCreating multiple complete datasets with different plausible imputed values, running the analysis on each, and pooling resultsStatistically valid approach for significant MAR missingness
Sentinel CodeA numeric or string placeholder (like -1 or 9999) used to encode missing data rather than leaving the field blankMust be converted to NaN before any analysis
Listwise DeletionRemoving any record that contains at least one missing valueOnly unbiased when data is MCAR and proportion missing is small
Isolation ForestA machine learning algorithm that detects outliers by measuring how few random splits are needed to isolate a pointMultivariate outlier detection for high-dimensional data
Local Outlier Factor (LOF)An algorithm that compares the local density of a point to the densities of its neighborsUseful for datasets with variable-density clusters
MADMedian Absolute Deviation — the median of absolute deviations from the median; robust to outliers in its own calculationUsed in the modified Z-score formula
Data LeakageWhen information from test data influences the training or cleaning process, artificially inflating measured model performanceCommon mistake when imputation statistics are fit on the full dataset before train-test split
Robust ScalingNormalizing features using median and IQR instead of mean and standard deviation, reducing the influence of extreme values on the scaled resultPreprocessing for distance-based algorithms when outliers remain in the data
Exploratory Data Analysis (EDA)The process of inspecting, visualizing, and summarizing a dataset before formal modeling to understand its structure and identify quality issuesThe stage where outlier and missing data detection naturally occurs

Frequently Asked Questions

An outlier is a data point that sits far from the rest of a dataset's values. Statistically, a common definition flags any value falling more than 1.5 times the interquartile range below Q1 or above Q3. But the statistical flag is a starting point for investigation, not a decision — context and domain knowledge determine whether a flagged value should be removed, corrected, or kept.
The most common methods are the IQR method (no normality assumption required), the Z-score method (assumes approximate normality), box plots and histograms for visual inspection, scatter plots for bivariate outliers relative to a relationship, and machine learning methods — Isolation Forest and Local Outlier Factor — for multivariate datasets with many variables. Using two methods together is standard practice because no single method catches every type.
No. Removal is appropriate only when an outlier is a confirmed data error and the true value cannot be recovered. Genuine extreme values — a very high-value customer, a patient with an unusual lab result, a rare but real transaction — should be kept, or treated with Winsorization, or separated into a subgroup for analysis. Removing real extreme values produces a model that understates the true variability in the data.
The IQR method calculates Q3 − Q1 to get the interquartile range. The lower fence is Q1 − 1.5×IQR and the upper fence is Q3 + 1.5×IQR. Values outside these fences are flagged as outliers. The method requires no assumption about the distribution's shape, which makes it the preferred starting point for exploratory data analysis on real, often skewed datasets.
MCAR means the probability of a value being missing has nothing to do with any variable in the dataset. MAR means the probability depends on other observed variables. MNAR means the probability depends on the unobserved value itself — people skip an income question specifically because their income is very high, for instance. The mechanism matters because it determines which imputation method will produce unbiased estimates.
Winsorization replaces values below a lower percentile with that percentile's value, and values above an upper percentile with that upper percentile's value. It keeps all records in the dataset while reducing the leverage of extreme values. Use it when outliers appear real but their exact magnitude is uncertain, or when a model is sensitive to scale and you do not want to lose observations by deleting them.
In linear regression, the least-squares objective minimizes the sum of squared residuals, so a single outlier with a large residual gets squared and contributes disproportionately to the cost function. This pulls the fitted line toward itself, changing slope and intercept estimates for all other records. High-leverage points — those with unusual x-values — can rotate the line significantly even if their y-residual is small.
Tree-based algorithms — decision trees, random forests, and gradient boosted trees like XGBoost and LightGBM — are the most robust because they split based on rank order, not raw magnitude. A value of 10,000 in a dataset where Q3 is 50 does not dominate a split differently from a value of 500; both sit above the split threshold. Distance-based algorithms (KNN, K-means, SVM) and regression-based models are the most sensitive.
KNN imputation finds the k records most similar to the record with the missing value, using other observed variables to measure similarity. For a missing numerical value it returns a weighted average of the neighbors' values; for a missing categorical value it returns the majority category among neighbors. It preserves the relationships between variables better than simple mean or median imputation, at the cost of higher computation.
Multiple imputation creates several versions of the dataset, each with different plausible imputed values, runs the analysis on each version, and combines results using Rubin's rules. This correctly accounts for uncertainty about the missing values, producing confidence intervals and p-values that reflect the fact that the imputed data is estimated, not known. It is the preferred method when missingness is substantial and the data is MAR, particularly in research contexts where statistical rigor matters.
Log transformation does not remove outliers — it compresses the scale so that extreme values have less influence on model estimates. If a right-skewed variable has values from $100 to $500,000, log-transforming converts those to roughly 4.6 to 13.1, dramatically reducing the leverage of the highest values. The transformation applies only to strictly positive values; zeros and negatives require an offset (log(x + 1) is a common approach for count data).
A sentinel code is a specific numeric or string value used to indicate that real data is absent — common examples include -1, -99, 0, 9999, "Unknown", and "N/A" stored as text. Legacy systems and survey software often use them rather than leaving fields blank. Sentinel codes must be identified and converted to proper NaN values before any statistical analysis, because treating them as real numbers will distort every summary statistic they appear in.
Data leakage occurs when information from the test set influences the training process. In data cleaning, the most common source is fitting imputation statistics — means, quartiles, KNN neighbor models — on the full dataset before splitting into train and test. If the test set's values inform the imputation, the model has effectively "seen" test data during training, producing optimistic performance estimates that fail in production. Always split first, then fit cleaning parameters on training data only.

Key references and further reading: Scikit-learn — Outlier Detection documentation · Pandas — Working with missing data · Statsmodels — MICE Multiple Imputation · UCI Machine Learning Repository — Practice datasets · Kaggle Datasets — Real-world data for practice · Variance Guide — Statistics Fundamentals · Expected Value Guide — Statistics Fundamentals