Data Warehousing and Data MiningUnit 411 min read
Data Preprocessing: Cleaning, Transforming & Feature Engineering
Unit 4 of Data Warehousing and Data Mining covers the critical preprocessing steps—data cleaning, integration, transformation, reduction, and discretization—that prepare raw data for mining. Learn why 80% of data science effort goes here, with real-world examples from eSewa fraud detection and Daraz recommendation syst
TAKEAWAYS:
- Dirty data is the enemy: Noise, missing values, and inconsistencies must be handled before analysis (e.g., eSewa’s duplicate transaction records).
- Integration merges sources: Combining transaction logs (Daraz) or sensor data (NTC power grids) requires careful schema alignment.
- Transformation reshapes data: Normalization, aggregation, and encoding (e.g., converting Kathmandu traffic routes into numerical features) unlock patterns.
- Reduction keeps what matters: Dimensionality reduction (PCA) speeds up mining—critical for NEPSE stock trend analysis with 100+ indicators.
- Discretization simplifies: Converting continuous data (e.g., Khalti’s transaction amounts) into bins improves rule clarity.
- Automation is key: Tools like Python’s
pandasor SQL’sCASE WHENhandle preprocessing at scale (e.g., Pathao’s ride-demand forecasting).
1. Why Preprocessing? The Dirty Data Problem
Raw data is messy:
- Noise: Typos in customer names (e.g., "Kathmandu" vs. "KathmanduU").
- Missing values: Ncell call-duration records with blank entries.
- Inconsistencies: Dates formatted as
DD/MM/YYYYvs.MM-DD-YYYYin bank loans. - Irrelevant data: A Daraz order’s shipping address may not predict customer churn.
Visual: The preprocessing pipeline (before mining):
flowchart LR
A["Raw Data\n(e.g., eSewa transactions)"] --> B["Cleaning\n(Handle noise/missing values)"]
B --> C["Integration\n(Merge datasets)"]
C --> D["Transformation\n(Scale, encode, aggregate)"]
D --> E["Reduction\n(Drop/extract features)"]
E --> F["Discretization\n(Bin continuous data)"]
F --> G["Ready for Mining\n(e.g., fraud detection)"]Real-world tie-in:
- eSewa’s fraud detection: Preprocessing flags duplicate payments by cleaning transaction IDs and merging user profiles.
- NTC’s power outage prediction: Sensor data is cleaned (removing spikes), integrated with weather logs, and binned into "high-risk" time slots.
2. Data Cleaning: Fixing the Mess
A. Handling Missing Values
Methods:
| Method | When to Use | Example |
|---|---|---|
| Deletion | <5% missing, random distribution | Drop rows with blank Ncell call durations. |
| Mean/Median Mode | Numerical data | Replace missing Khalti transaction amounts with median. |
| Prediction Models | Critical data (e.g., hospital records) | Use regression to estimate missing Daraz product ratings. |
| Flagging | Missingness is meaningful | Mark "unknown" in NEPSE stock splits as a separate category. |
Worked Example:
Problem: A dataset of Pathao ride requests has 10% missing fare_amount values. The mean fare is ₹120, median is ₹100.
Solution:
# Using median (less sensitive to outliers)
df['fare_amount'].fillna(100, inplace=True)
Why median? Pathao’s fares are skewed (some rides are ₹50, others ₹500). Median preserves the central tendency better.
B. Noise Reduction
Techniques:
- Binning: Group continuous values (e.g., age → "18-25", "26-35").
- Smoothing: Replace outliers with percentiles (e.g., cap Ncell call durations at 99th percentile).
- Clustering: Use DBSCAN to detect and remove anomalies (e.g., Daraz orders with impossible shipping times).
Visual: Outlier treatment in NEPSE stock prices:
graph LR
A["Raw Prices\n(₹100-₹5000)"] --> B["Detect Outliers\n(>₹3000 = 1% of data)"]
B --> C["Cap at 99th Percentile\n(₹2800)"]
C --> D["Cleaned Data\n(₹100-₹2800)"]Real Picture:
3. Data Integration: Merging Datasets
Challenges:
- Schema mismatches: eSewa’s
user_idvs. Khalti’scustomer_code. - Temporal gaps: Daraz order data vs. inventory logs.
- Duplicate records: NTC’s power consumption data with the same meter ID.
Solutions:
| Problem | Technique | Example |
|---|---|---|
| Different IDs | Key mapping (e.g., SQL JOIN) |
SELECT * FROM eSewa LEFT JOIN Khalti ON eSewa.user_id = Khalti.customer_code |
| Time misalignment | Resampling (e.g., hourly → daily) | Aggregate Pathao rides per hour into daily demand. |
| Duplicates | Deduplication (hashing, clustering) | Use DISTINCT or GROUP BY in SQL. |
Worked Example: Problem: Merge Daraz order data (100K rows) with customer reviews (50K rows) to predict churn. Steps:
- Align keys: Both tables have
customer_idbut different formats (e.g., "CUST123" vs. "123"). - Join:
SELECT o.order_id, c.review_rating, o.amount_spent FROM orders o INNER JOIN customers c ON o.customer_id = REPLACE(c.customer_id, 'CUST', '') WHERE c.review_rating IS NOT NULL; - Result: 45K merged rows for churn analysis.
4. Data Transformation: Reshaping for Patterns
A. Normalization/Scaling
Why? Algorithms like K-means assume features are on similar scales (e.g., age vs. income). Methods:
| Method | Formula | Use Case |
|---|---|---|
| Min-Max | Scaling Daraz product prices (₹100–₹5000) to 0–1. | |
| Z-Score | Normalizing NEPSE stock returns. | |
| Log Transform | Reducing skew in Khalti transaction amounts. |
Visual: Min-Max scaling on Daraz prices:
graph TD
A["Raw Prices\n(₹100, ₹5000)"] --> B["Min-Max\n(₹100→0, ₹5000→1)"]
B --> C["Scaled Data\n(0 to 1)"]B. Encoding Categorical Data
Problem: Algorithms need numbers (e.g., "Kathmandu" vs. "Lalitpur" as 0/1). Methods:
| Method | Example | When to Use |
|---|---|---|
| Label Encoding | Kathmandu=0, Lalitpur=1 | Ordinal data (e.g., "low/medium/high risk"). |
| One-Hot Encoding | Kathmandu=[1,0], Lalitpur=[0,1] | Nominal data (e.g., Daraz product categories). |
| Binary Encoding | Kathmandu=001, Lalitpur=010 | High-cardinality (e.g., 100+ cities). |
Worked Example: Problem: Encode customer locations for a Pathao demand prediction model. Solution (One-Hot):
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False)
locations_encoded = encoder.fit_transform([["Kathmandu"], ["Lalitpur"], ["Bhaktapur"]])
# Output: [[1,0,0], [0,1,0], [0,0,1]]
C. Aggregation
Example: Summarize Ncell call records by hour to predict peak usage.
SELECT
HOUR(call_time) AS hour_of_day,
COUNT(*) AS call_count
FROM call_records
GROUP BY HOUR(call_time)
ORDER BY hour_of_day;
Output:
| hour_of_day | call_count |
|---|---|
| 18 | 12,000 |
| 20 | 15,000 |
5. Data Reduction: Less Is More
A. Dimensionality Reduction
Goal: Reduce features while retaining 95% variance (e.g., 100 stock indicators → 10). Methods:
| Method | How It Works | Example |
|---|---|---|
| PCA | Linear projection to top components | Reduce NEPSE’s 50 indicators to 5. |
| Feature Selection | Select top-k features by importance | Use SelectKBest for Daraz’s churn predictors. |
Visual: PCA on NEPSE data (3D → 2D):
B. Discretization
Why? Convert continuous data into bins (e.g., "low/medium/high risk"). Example: Bin Khalti transaction amounts into risk categories:
| Range (₹) | Risk Level |
|---|---|
| 0–1000 | Low |
| 1001–5000 | Medium |
| 5001+ | High |
Code:
import pandas as pd
df['risk_level'] = pd.cut(df['amount'],
bins=[0, 1000, 5000, float('inf')],
labels=['Low', 'Medium', 'High'])
6. Real-World Applications
A. eSewa: Fraud Detection
- Cleaning: Remove duplicate transactions using
GROUP BY transaction_id. - Integration: Merge user profiles with payment logs.
- Transformation: Encode user locations (one-hot) and normalize amounts.
- Reduction: Use PCA to reduce 20 features to 5 for faster fraud scoring.
B. Daraz: Recommendation System
- Cleaning: Fill missing product ratings with the user’s average rating.
- Integration: Join order history with product categories.
- Transformation: Encode categories (one-hot) and scale prices.
- Discretization: Bin order amounts into "small/medium/large" for rule mining.
C. NTC: Power Outage Prediction
- Cleaning: Smooth sensor data with a moving average (remove noise).
- Integration: Merge weather data with outage logs.
- Transformation: Encode weather conditions (e.g., "rainy"=1, "sunny"=0).
- Reduction: Use feature selection to keep only top 10 predictors.
Exam Tip
What examiners test:
- Definitions: Know the difference between cleaning, integration, and transformation.
- Methods: Be ready to apply:
- Missing value techniques (e.g., mean vs. prediction).
- Encoding schemes (label vs. one-hot).
- Dimensionality reduction (PCA vs. feature selection).
- SQL/Python: Expect questions on:
- Cleaning with
COALESCEorfillna(). - Joins for integration.
- Aggregation (
GROUP BY,COUNT).
- Cleaning with
- Real-world links: Relate preprocessing to:
- Fraud detection (eSewa).
- Recommendations (Daraz).
- Predictive maintenance (NTC).
- Pitfalls: Avoid:
- Over-cleaning (losing meaningful missingness).
- Leakage (e.g., using future data to impute missing values).
Sample Exam Question: "A dataset of Pathao rides has missing fare amounts and categorical locations. Describe how you would preprocess it for a churn prediction model. Include SQL/Python snippets for cleaning and encoding."
Model Answer Outline:
- Cleaning: Handle missing fares with median, remove outliers.
- Integration: Join ride data with user profiles.
- Transformation: One-hot encode locations, normalize fare amounts.
- Reduction: Use PCA if >50 features.
- Discretization: Bin fares into "low/medium/high" for rule mining.
Key Formula to Remember: For Min-Max Scaling:
Real Picture:
Based on the TU BITM syllabus for Data Warehousing and Data Mining (IT274), unit 4.
Discussion
Loading…