01 / 22

Data Cleaning &
Preprocessing

Learn to transform messy, real-world data into clean, analysis-ready datasets: handling missing values, removing duplicates, and standardizing formats.

Business Analytics

Why Clean Data Matters

Every business decision powered by data is only as good as the data itself. Studies show that data scientists spend roughly 80% of their time cleaning and preparing data, and only 20% on actual analysis.

Data cleaning is the foundational skill that separates meaningful insights from misleading conclusions.

Key Definitions

Data Cleaning
Detecting and correcting (or removing) corrupt, inaccurate, or irrelevant records from a dataset.
Preprocessing
Transforming raw data into a structured format suitable for analysis: encoding, scaling, and reshaping.
Data Quality
The degree to which data is accurate, complete, consistent, timely, and valid for its intended use.

The Data Quality Pipeline

Raw Data Messy, incomplete Clean Fix errors, gaps Transform Encode, scale Ready Analyze! Step 1: Cleaning Step 2: Preprocessing Missing values, duplicates, outliers, typos Normalization, encoding, feature selection

Five Pillars of Data Quality

1
Accuracy: Values correctly represent real-world facts.
2
Completeness: No critical fields are missing data.
3
Consistency: Data follows the same format and rules throughout.
4
Timeliness: Data is up-to-date and relevant to the current context.
5
Validity: Data conforms to the expected type, range, and constraints.

Types of Dirty Data

Missing Values
Blank cells, NULL entries, or placeholder text like "N/A" that represent absent data.
Duplicates
Identical or near-identical records that inflate counts and skew averages.
Inconsistencies
Same entity recorded differently: "NY" vs "New York" vs "new york".
Outliers & Invalid Data
Values far outside the expected range (e.g., age = 999) or that violate constraints (e.g., salary = \(-50{,}000\)).

Cleaning vs Preprocessing

Aspect Data Cleaning Data Preprocessing
Goal Fix errors and fill gaps Transform data for models
Focus Quality and correctness Format and structure
Examples Remove duplicates, fix typos Normalize, encode categories
When First (before preprocessing) After cleaning is complete
Analogy Washing vegetables Chopping and seasoning

Handling Missing Values

Delete
Remove entire rows or columns with too many missing values. Best when < 5% of data is affected.
Impute (Mean/Median)
Replace missing numeric values with the column's mean \(\bar{x}\) or median. Preserves dataset size.
Impute (Mode)
Replace missing categorical values with the most frequent category (mode). Good for text fields.

The Cleaning Checklist

1
Profile the data: Check dimensions, data types, and summary statistics.
2
Identify missing values: Count NULLs per column. Decide: delete or impute?
3
Remove duplicates: Find and drop exact or near-duplicate rows.
4
Fix inconsistencies: Standardize text casing, date formats, and categories.
5
Detect outliers: Use the IQR rule: values below \(Q_1 - 1.5 \times \text{IQR}\) or above \(Q_3 + 1.5 \times \text{IQR}\) are suspect.
6
Validate: Re-check summary stats and row counts to confirm the fix worked.

Example 1: Spotting Problems

You receive this customer dataset. Can you spot the issues?

ID | Name | Age | City | Spent 1 | Alice Smith | 28 | New York | 150.00 2 | Bob Jones | 34 | NULL | 200.50 3 | alice smith | 28 | New York | 150.00 4 | Carol Lee | -5 | los angeles | 75.00 5 | Dave Kim | 41 | LA | NULL

Example 2: Fixing the Data

1
Remove duplicate: Drop row 3 (identical to row 1 after case normalization).
2
Impute missing city: Row 2's city is NULL: investigate or flag for follow-up.
3
Fix invalid age: Row 4 has age = \(-5\). Replace with NULL and impute using median age: \(\tilde{x} = 34\).
4
Standardize cities: Map "LA", "los angeles" → "Los Angeles". Apply title case throughout.
5
Handle missing Spent: Row 5 is NULL: impute with mean: \(\bar{x} = \frac{150 + 200.5 + 75}{3} \approx 141.83\).

Example 3: Normalization

After cleaning, we often need to normalize numeric columns so they share a common scale. This prevents large-valued features from dominating analysis.

Example: If ages range from 28 to 41, then for age = 34:

Z-Score Standardization

Example: If the "Spent" column has \(\mu = 141.83\) and \(\sigma = 51.26\), then for a customer who spent \(\$200.50\):

Encoding Categorical Data

Most analytical tools require numeric input. Categorical variables like "City" or "Color" must be encoded into numbers.

Label Encoding
Assign each category a unique integer: "Red" = 0, "Blue" = 1, "Green" = 2. Simple but implies false ordering.
One-Hot Encoding
Create a binary column for each category: "Is_Red", "Is_Blue", "Is_Green". No false ordering, but adds columns.

Outlier Detection: IQR Method

Q1 Median Q3 IQR = Q3 - Q1 Lower Fence Upper Fence Outlier Outlier

Common Mistakes

✕ Deleting Too Much
Removing every row with any missing value can shrink your dataset dramatically, losing valuable information.
✕ Ignoring Data Types
Treating zip codes or IDs as numbers instead of categories leads to meaningless calculations like "average zip code".
✕ Blind Outlier Removal
Automatically removing all outliers without investigation: some outliers are real and important business signals.
✕ Skipping Validation
Not re-checking data after cleaning. New errors can be introduced during imputation or transformation steps.

Summary of Techniques

Technique When to Use Watch Out For
Delete rows/cols < 5% missing Data loss
Mean/median imputation Numeric columns Reduces variance
Mode imputation Categorical columns Over-represents mode
Min-Max normalization Bounded features Sensitive to outliers
Z-Score standardization Unbounded features Assumes approximately normal dist.
One-hot encoding Nominal categories High cardinality = many cols

Question 1 of 5

A dataset has 10,000 rows. The "Phone Number" column has 8,200 missing values. What is the best approach?

Question 2 of 5

Which formula correctly performs Min-Max normalization?

Question 3 of 5

A "Color" column contains values: Red, Blue, Green, Yellow. You need to prepare it for a machine learning model. Which encoding avoids implying a false ordering?

Question 4 of 5

A dataset records customer ages. The values for \(Q_1 = 25\), \(Q_3 = 45\), so \(\text{IQR} = 20\). Using the IQR rule, which age would be flagged as an outlier?

Question 5 of 5

You computed a Z-score of \(z = -2.3\) for a data point. What does this mean?