Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 4 of 9
Systematic Data Cleaning: Inconsistent Types, Duplicates & Normalization
Real-world data is inherently messy: mixed types, non-breaking whitespace, corrupted timestamps, duplicate records, and inconsistent casing. Machine learning models will fail silently or learn spurious noise if training data contains corrupted records. Establishing an automated, idempotent cleaning pipeline is the first defensive perimeter of professional ML engineering.
End-to-End Idempotent Data Sanitization Pipeline
import pandas as pd
import numpy as np
# Synthetic dirty enterprise CRM export
raw_records = {
'customer_id': ['C101', 'C102', 'c101 ', 'C103', 'C104', 'C104', 'C105'],
'signup_date': ['2026-01-15', '15/01/2026', '2026-01-15', 'INVALID_DATE', '2026-02-01', '2026-02-01', None],
'annual_revenue': ['$125,000.50', ' $45000.00 ', '$125,000.50', 'N/A', '$85,200', '$85,200', '-$1000.00'],
'region': ['North America', 'EMEA', 'north america', 'APAC', 'LATAM', 'LATAM', 'Unknown'],
}
df_dirty = pd.DataFrame(raw_records)
def clean_crm_records(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
# 1. Normalize identifiers & strip whitespace
df['customer_id'] = df['customer_id'].astype(str).str.strip().str.upper()
# 2. Deduplicate based on primary key
df = df.drop_duplicates(subset=['customer_id'], keep='first')
# 3. Clean and parse currency strings to numeric float
df['annual_revenue'] = (
df['annual_revenue']
.astype(str)
.str.replace(r'[$,]', '', regex=True)
.str.strip()
)
df['annual_revenue'] = pd.to_numeric(df['annual_revenue'], errors='coerce')
# Reject logically impossible negative revenues
df.loc[df['annual_revenue'] < 0, 'annual_revenue'] = np.nan
# 4. Standardize datetime formats
df['signup_date'] = pd.to_datetime(df['signup_date'], format='mixed', errors='coerce')
# 5. Clean categorical casing & map synonyms
df['region'] = df['region'].astype(str).str.strip().str.upper()
synonym_map = {'NORTH AMERICA': 'NA', 'UNKNOWN': np.nan}
df['region'] = df['region'].replace(synonym_map)
return df
cleaned_df = clean_crm_records(df_dirty)
print("Sanitized Production DataFrame:")
print(cleaned_df.to_string())Pro Tip: Enforce Data Schemas with Pandera or Pydantic
Instead of relying on manual `assert` statements, define an explicit schema using `pandera`. A Pandera `DataFrameSchema` automatically checks column types, null tolerances, and value ranges (e.g. `pa.Check.greater_than(0)`) at runtime, raising informative schema violation errors before modeling begins.
MlCleaningDirtyData Visual Representation
Hands-On Challenge: Fuzzy String Matching Deduplication
Use Python's `difflib.get_close_matches` or `thefuzz` library to cluster and standardize messy company name strings (e.g., 'Google Inc.', 'Google LLC', 'google', 'Google Corp.') into a single canonical entity.
Quick Quiz & Key Concept Checks
Common Pitfall: Blindly Dropping Records with Any Null
Calling `df.dropna()` without column inspection can easily discard 80%+ of an enterprise dataset if even one non-critical metadata column has a high null rate. Always specify target subsets: `df.dropna(subset=['critical_feature_1', 'target_y'])`.