Lesson 8 of 9
Mini Project: Production Wrangling of a Messy Financial Dataset
Apply all Module 2 wrangling techniques to clean, normalize, impute, and enrich a messy raw financial lending dataset. The workflow parses dirty currency strings, resolves mixed timestamp formats, optimizes memory footprint with PyArrow/categories, handles missing values using domain-specific rules, and outputs an audit-compliant, ML-ready feature matrix.
Complete Production Financial Wrangling Script
import pandas as pd
import numpy as np
# Create synthetic raw financial lending dataset
np.random.seed(42)
n = 5000
raw_data = pd.DataFrame({
'loan_id': [f"LNK_{i:06d}" for i in range(n)],
'applicant_income': np.random.choice(['$45,000.00', ' $72,500 ', 'UNKNOWN', '$120,000', None], size=n),
'credit_score': np.random.choice([720, 680, 590, 810, 9999, -1], size=n, p=[0.4, 0.3, 0.2, 0.05, 0.025, 0.025]),
'loan_amount': np.random.uniform(5000, 50000, size=n),
'employment_length': np.random.choice(['10+ years', '< 1 year', '3 years', '5 years', 'n/a'], size=n),
'defaulted': np.random.choice([0, 1], size=n, p=[0.92, 0.08])
})
def production_financial_pipeline(df: pd.DataFrame) -> pd.DataFrame:
clean = df.copy()
# 1. Clean income strings to numeric float
clean['applicant_income'] = (
clean['applicant_income']
.astype(str)
.str.replace(r'[$,]', '', regex=True)
.str.strip()
)
clean['applicant_income'] = pd.to_numeric(clean['applicant_income'], errors='coerce')
# Impute missing income with median
income_median = clean['applicant_income'].median()
clean['income_was_missing'] = clean['applicant_income'].isna().astype('uint8')
clean['applicant_income'] = clean['applicant_income'].fillna(income_median)
# 2. Clean credit score domain errors (valid range: 300 to 850)
clean.loc[(clean['credit_score'] < 300) | (clean['credit_score'] > 850), 'credit_score'] = np.nan
clean['credit_score'] = clean['credit_score'].fillna(clean['credit_score'].median())
# 3. Clean employment length ordinal mapping
emp_map = {
'< 1 year': 0.5,
'3 years': 3.0,
'5 years': 5.0,
'10+ years': 10.0,
'n/a': np.nan
}
clean['employment_years'] = clean['employment_length'].map(emp_map)
clean['employment_years'] = clean['employment_years'].fillna(0.0)
# 4. Feature Engineering: Debt-to-Income Proxy Ratio
clean['debt_to_income'] = clean['loan_amount'] / np.maximum(clean['applicant_income'], 1000.0)
# 5. Drop raw string columns and optimize types
clean = clean.drop(columns=['employment_length'])
clean['credit_score'] = clean['credit_score'].astype('uint16')
clean['applicant_income'] = clean['applicant_income'].astype('float32')
clean['loan_amount'] = clean['loan_amount'].astype('float32')
clean['defaulted'] = clean['defaulted'].astype('uint8')
return clean
processed_df = production_financial_pipeline(raw_data)
print("=== PRODUCTION PROCESSED FEATURE STORE READY ===")
print(processed_df.info())
print("\nFirst 5 processed records:")
print(processed_df.head())Pro Tip: Preserve the Raw Ingestion Pipeline Immutably
Never overwrite raw data files in your data lake. Always write wrangling outputs to a versioned output path (e.g., `s3://lake/silver/loans_v2/`) so that if a bug is discovered in your cleaning logic, the raw source of truth remains pristine and can be reprocessed without data loss.
MlDataCleaningProject Visual Representation
Hands-On Challenge: Automated Data Validation Report
Write a verification function `audit_processed_data(df)` that asserts zero null values exist, verifies all columns match expected numeric dtypes, and outputs summary statistics for the target variable distribution.
Quick Quiz & Key Concept Checks
Common Pitfall: Hardcoding Imputation Statistics in Production Pipelines
If the median income computed on the training set is not saved as a pipeline artifact, scoring new live users in production will either fail or compute the median of the single-row inference batch (which is just that row's value!). Save your imputer parameters inside a Scikit-Learn Pipeline.