Data Cleaning -
MISSING DATA
Lecture 11
CMSC 320: Introduction to Data Science
So far, we have talked about
Outlier data is a numeric value that is much larger or smaller than other values in the same feature. Outlier data is usually defined as two or three standard deviations from the feature mean.
Duplicate data are two or more identical instances in a dataset. Duplicate instances are usually erroneous and should be removed.
NEXT: Missing data
Missing data refers to instances in a dataset where values are not recorded or incomplete. In databases, it's represented as NULL, while in Python, it appears as NaN, NaT, None, or blank values.
2
Dirty Data
Missing, outlier, and duplicate data are collectively called dirty data. (Ref: Zybook 5.4)
3
Dirty data creates bias and inefficiencies in data analysis.
Recap from last lecture: How to handle Outlier Data
Winsorization: Instead of removing the outlier, replace extreme values with a chosen percentile value.
Example:
Original salaries:
[40,000, 45,000, 50,000, 55,000, 500,000]
Using Winsorization (95th percentile):
[40,000, 45,000, 50,000, 55,000, 70,000]
The extreme value 500,000 is replaced with the percentile cutoff (70,000).
Why use it?
Python: Use the winsorize function from the scipy.stats.mstats module.
How to handle Outlier Data: Replacing Outlier
Courtesy: Breakthrough Tech ML course
Winsorization keeps the outlier in the dataset but limits its effect by replacing it with a less extreme value
Scipy to winsorize data (cap extreme values)
Next Topic: Missing Data
Check Missing Data
df.isnull().any().any()
Back to: Missing Data
8
Age |
21 |
19 |
NaN |
22 |
20 |
21 |
Why is our data missing?
Types of Missing Data (called “Mechanisms”)
Missing data can be categorized into 3 categories:
Types of Missing Data (called “Mechanisms”)
Missing completely at random (MCAR)
Missing at random (MAR)
Missing not at random (MNAR)
*Observed mean: already collected
Example: MCAR vs MAR vs MNAR
11
*Observed mean: already collected
1. MCAR: Data missing Completely at Random
12
"Example 1": Income and Age are missing due to random technical errors (unsaved forms), with no relation to the observed data (Age, Gender, Favorite Color) or the actual missing values.
"Example 2": Imagine a big test where each student gets different random questions.
Missingness is entirely random and unrelated to any variable.
13
Age | Gender | Income | Favorite Color |
25 | Male | | Blue |
30 | Female | 50,000 | Red |
22 | Male | 45,000 | Red |
28 | Female | 60,000 | Green |
| Male | 55,000 | Yellow |
Notice: In this example, each student receives a random subset of questions, so the missing questions are randomly distributed and not influenced by student characteristics or any other observed data.
Ref: https://www.publichealth.columbia.edu/research/population-health-methods/missing-data-and-multiple-imputation
2. MAR: Data missing Completely at Random
14
The missingness is related to some of the observed data but not the missing data itself
2. MAR:Understanding Characteristics
Age | Gender | Physical Health Score | Mental Health Status |
95 | Female | 80 | |
70 | Male | 75 | Mild Depression |
30 | Female | 90 | No Issues |
98 | Male | 85 | |
45 | Female | 88 | Moderate Anxiety |
Example 1: In a medical study, older patients are more likely to skip mental health questions. The missingness depends on age (an observed variable), not on their actual mental health condition.
Younger people (e.g., Age < 30) are less likely to report income.
3. MNAR: Data Missing Not at Random (MNAR)
When data is not missing at random, the chance of it being missing depends on the missing values themselves, not just the observed data.
16
3. MNAR:Understanding Characteristics
This is the most challenging type of missing data to handle, as the missingness is related to the unobserved (missing data) data itself!
Example 1: In a financial survey, people with very high incomes are less likely to report their income because they prefer to keep it confidential.
People with very high or very low incomes are less likely to report income.
Age | Gender | Occupation | Income |
25 | Male | Engineer | 70,000 |
30 | Female | Doctor | |
22 | Male | Student | 20,000 |
28 | Female | Lawyer | |
45 | Male | Executive | |
(1) MCAR: Data Missing at Completely Random
18
HOW TO HANDLE
Data Missing at Random
Solution 1: Drop it
For data that is categorical, it’s fine! “Missing” can just become a new category.
Ex: If our category is major, we could have { “Computer Science”, “Philosophy”, “Did not answer” }
For numerical data, most algorithms we use cannot accept NaN. So what do we do?
19
If 1% of your data has missing rows and you have a terabyte of it, just drop all rows that have missing stuff.
df.dropna()
When Is It Safe to Drop Missing Data?
No strict cutoff; depends on context.
% Missing Data | Common Approach | Notes |
< 5% | Listwise deletion is usually fine | Often negligible bias if MCAR |
5–10% | Acceptable but check sensitivity | Prefer simple imputation |
10–20% | Risky | Use multiple imputation / model-based |
> 20% | Avoid deletion | Investigate missingness mechanism |
Why no fixed rule?
Practical Checklist Before Dropping Data
More Strategies to Handle (MCAR) data
Relatively straightforward as the missingness is random and unrelated to any data, so the observed data remains representative and unbiased.
Strategies:
Solution 2: Listwise or Pairwise Deletion
Pairwise Deletion: Lets you keep more of your data by only removing only the data points that are missing from any analyses. It will create an uneven sample size for each of the variables but helpful when having a small sample or a large proportion of missing values for some variables.
22
Listwise Deletion: Remove any entire rows with missing data. This works well when the proportion of missing data is small.
train_1 = train.copy()
train_1.dropna()
All methods in pandas like mean, sum, etc. intrinsically skip missing values.
train_2 = train.copy()
train_2['Item_Weight'].mean()
Solution 3(A): Apply Imputation!
Imputation is the process of replacing missing values with estimates (new values).
Data may be imputed in several ways:
23
Mean/ Median/Mode Imputation | Imputation Using (Mean/Median/Mode) Values
|
Hot Imputation | The value is selected from other instances in the same dataset. |
Cold Imputation: | The value is selected from other instances in the different dataset (use external data). |
Bayesian Imputation, Multiple imputation and many more…. | |
Use: df_imputed = df.fillna(value); value could be fixed no, df.mean() etc. Also some options: df.fillna(method='bfill'), df.fillna(method='ffill') to impute previous or next valid value | |
Examples:
Mean Imputation: Set the value to the mean of that column
For example, if a height is missing, fill in 5’5’’
Mode Imputation: Fill in with the most common value
When to use Mean vs. Median vs. Mode
Notes: Mode can be used for numeric data, but it is more appropriate for categorical variables or when a clear most frequent value exists.
It's generally advisable: Use Mean/Median/Mode Imputation when no more than 5% of the variable contains missing data.
Solution 3(B): Hot-Deck Imputation
Fill missing values using data from similar rows in the same dataset.
How It Works
Example If a student is missing a grade for CMSC320, find a student with similar academic history and use their CMSC320 grade.
Age Example: Identify similar individuals (e.g., based on gender or other characteristics). Use a similar person (donor) to fill the missing age.
Solution 3(C): Multiple Imputation (MI)
(common technique for MAR)
Generate plausible values for each missing value (imputation step).
2. Analyze each dataset separately (analysis step).
3. Combine results to reflect uncertainty (pooling step).�
Goal: Produce valid statistical inference despite missing data.�
Advantages
Example Use Age and Gender to predict missing Income values multiple times, then combine the results
Multiple Imputation: Example
Scenario: You survey people about height and weight, but some participants skip one or both questions.
Example: If weight is missing for taller individuals, use height and gender to predict a range of plausible weights in each dataset.
Multiple Imputation
Remember: We do not pool into a single imputed value.� We pool the analysis results, not the raw filled-in values.
The goal is valid inference ; not just one final “best guess.”
The fancyimpute library in Python is commonly used for multiple imputation.
How many imputations for MI?
(2) MAR: Data Missing at Random
30
HOW TO HANDLE
Handling Missing Completely at Random (MAR) data
Strategies:
For MAR: Regression Imputation
Use a regression model to predict missing values based on other observed variables.
Example: Predict missing Income values using Age and Education.
For MAR: K-Nearest Neighbors (KNN) Imputation
Replace missing values with the average of the nearest neighbors in the dataset.
from sklearn.impute import KNNImputer
imputer = KNNImputer(n_neighbors=3, weights='distance')
https://www.geeksforgeeks.org/handling-missing-data-with-knn-imputer/#
(3) MNAR: Data Missing Not at Random
When data is not missing at random, the chance of it being missing depends on the missing values themselves, not just the observed data.
34
HOW TO HANDLE
Different Categories of MNAR
Data not missing at random is subject to some sort of systematic bias
35
36
We can use information from similar time periods or frames to estimate or impute missing income values over time.
E.g,. Look at income patterns from similar months in the past
Imputation using framing data means filling in those missing values based on similar information from other observations.
Use domain knowledge or historical data to impute missing values. Example: Use data from the same time period in previous weeks or months to fill in missing values.
B. Handling Data Missing Based on Value
37
Bayesian Imputation (MAR and MNAR)
38
A statistical technique used for imputing missing data in a dataset using Bayesian methods.
Bayesian Imputation
For categorical data, for example:
Evaluate each of these for each feature and assign!
Xmissing = The missing value that we’re trying to impute
Xobserved= The data that we observed previously
|
|
Bayesian Imputation: example
Suppose you have a dataset about fruits with two features: color and shape. You want to impute the missing values for the "Type of Fruit" category.
40
You want to fill in the missing 'Type of Fruit' values using Bayesian imputation, which involves estimating the probabilities of each fruit type based on the observed data.
Expert Input
Use domain knowledge to make informed assumptions about the missing data.
Example: If high-income individuals are less likely to report their income, manually adjust the imputed values.
C. Handling Missing Data: Dealing With Boundary Conditions
Depends on the circumstances.
42
Note: Extrapolation means using existing data to make predictions or estimates for values that are outside the range of the data you have.
Example: Dealing With Boundary Conditions
Example: Temperature Sensor Data: Imagine you have a dataset that records outdoor temperatures (in degrees Celsius) over time. However, the sensor used to collect data has a known boundary condition—it can't measure temperatures below -10°C or above 40°C accurately.
43
Solution 1: Exclude Data at the Boundary: Exclude temperatures outside the range of -10°C to 40°C if you're focusing on normal weather conditions.
Solution 2: Extrapolate Data: Use statistical methods to estimate temperatures beyond -10°C and 40°C for predictions outside sensor limits.
Solution 3: Acquire More Data: Use sensors that measure extreme temperatures if you need accurate readings beyond -10°C and 40°C.
Note: Extrapolation means using existing data to make predictions or estimates for values that are outside the range of the data you have.
Incorrect Data
44
NEXT TOPIC
Incorrect Data
What does it mean for data to be incorrect?
45
Types of Incorrect Data:
Detecting incorrect data involves looking for anomalies or patterns that deviate from what's expected or reasonable in your dataset.
Detecting Incorrect Data
46
Attractors: Check for unusual spikes or concentrations of data points in specific categories or values.
Example: A disproportionate number of individuals report height as exactly 6’0”, suggesting rounding rather than true distribution.
Discontinuities: Look for abrupt changes/ shift or discontinuities in your data.
Example : Once the limit for how much weed constituted a felony changed, there was a significant discontinuity centered around that threshold (People might adjust their behavior based on the new legal limit).
How do we find data that’s incorrect?
Detecting Incorrect Data: Implausible Modes
Examples:
Detecting Incorrect Data: Boundary Conditions
Examples:
These often indicate data entry errors or coding issues.
48
Data Outside Valid Bounds Check for values that fall outside the logical or possible range.
Boundary Conditions (Artificial Caps)
Sometimes limits are created by systems, not reality.
Instrument Limits
Database Constraints
Survey Limits
Survey only allowed ages up to 24
The radiation sensor cannot measure above 120 units
Detecting Incorrect Data: Instrument Error
Sometimes data problems occur because the measurement device itself is failing or miscalibrated.
How to repair:
Important: This approach only works if the type of error is clearly understood.
50
Problems or mistakes that can happen with measurement instruments or devices
This adjustment might involve shifting values, scaling them, or applying other corrective measures.
How to Deal with Incorrect Data
Great Examples of Lies
52
SUMMARY
Messy Data: can be due to Missing values
Combined columns carefully �
Multiple joined tables, carefully, ensuring file formats match.�
Changing labels or formats: Adapt to changes in labeling schemes
Data Cleaning Essentials
SUMMARY
—-THE END—-
Detecting Incorrect Data: Identify issues like attractors, discontinuities, strange modes, and data outside valid bounds.
Repairing Instrument Errors: Correct data from malfunctioning sensors based on past data or similar sensors.
Signs of Boundary Conditions: Look for sudden changes or gaps in data and observe patterns in visualizations.
Data cleaning is a crucial step in data analysis to ensure the accuracy and reliability of your results.
54