Data Warehousing and Data MiningUnit 313 min read
Data Preprocessing: Cleaning, Integration, Transformation & Reduction
Unit 3 of Data Warehousing and Data Mining covers the critical preprocessing steps—data cleaning, integration, transformation, and reduction—that prepare raw data for mining and warehousing, with real-world examples from Nepalese apps like eSewa and Daraz.
What is Data Preprocessing?
Data preprocessing is the first and most crucial step in data mining and warehousing. It involves preparing raw data to make it consistent, accurate, and useful for analysis. Without preprocessing, even the best algorithms will fail because:
- Raw data is messy (missing values, noise, inconsistencies).
- Different sources (e.g., eSewa transactions vs. Daraz orders) use different formats.
- Business questions require specific transformations (e.g., converting dates to quarters for NEPSE stock analysis).
Key Idea:
"Garbage in, garbage out (GIGO)." Preprocessing ensures the input data is high-quality, so mining results are reliable.
Why Preprocess Data? (Real-World Pain Points)
1. eSewa’s Failed Payments
eSewa processes millions of transactions daily, but:
- Inconsistent formats: Some users enter dates as
2023/12/31, others as31-12-2023. - Missing data: Phone numbers may be empty for some users.
- Noise: Typos in merchant IDs (e.g.,
MERCH123vs.MERCH_123). Result: Without preprocessing, eSewa’s fraud detection model would flag false positives, hurting user trust.
2. Daraz’s Out-of-Stock Errors
Daraz’s inventory system suffers from:
- Duplicate entries: Same product listed twice due to manual uploads.
- Incomplete data: Some listings lack
priceorstock_quantity. - Dirty data: Product names like
"iPhone 13 Pro (128GB) [Old Stock]"vs."iPhone 13 Pro 128GB". Result: Customers see "Out of Stock" even when items are available, increasing cart abandonment.
3. NTC’s Traffic Route Optimization
NTC uses GPS data from buses to optimize routes, but:
- Missing timestamps: Some buses don’t log exact departure times.
- Sensor noise: GPS coordinates jump due to signal drops.
- Inconsistent units: Speed recorded in
km/handm/sin different logs. Result: Without cleaning, the route-planning algorithm would suggest inefficient paths, wasting fuel.
The 4 Key Steps of Data Preprocessing
Preprocessing follows a pipeline (visualized below). Each step refines data for the next.
flowchart LR
A["Raw Data"] --> B["Data Cleaning"]
B --> C["Data Integration"]
C --> D["Data Transformation"]
D --> E["Data Reduction"]
E --> F["Cleaned Data Ready for Mining"]Step 1: Data Cleaning (Fixing Errors)
Definition: Removing or correcting inaccuracies, inconsistencies, and missing values in data.
Why? Dirty data leads to wrong conclusions. Example: If NEPSE’s stock data has missing close_price values, trend analysis fails.
Common Cleaning Techniques
| Problem | Solution | Example (Nepal Context) |
|---|---|---|
| Missing values | Impute (fill) or remove rows/columns | Fill missing user_age in eSewa data with median age. |
| Noise | Smoothing (e.g., averaging) | Smooth GPS noise in Pathao driver routes. |
| Inconsistent data | Standardize formats | Convert all dates to YYYY-MM-DD for NTC logs. |
| Outliers | Remove or cap values | Remove a Daraz order with price = 0 (typo). |
Worked Example: Cleaning eSewa Transaction Data
Dirty Data Sample:
| Transaction_ID | Amount (NPR) | Date | Merchant_ID | User_Phone |
|---|---|---|---|---|
| TXN001 | 500 | 2023/12/31 | MERCH123 | 9841234567 |
| TXN002 | NULL | 31-12-2023 | MERCH_123 | 984123456 |
| TXN003 | 1200 | 2023-12-31 | MERCH123 | NULL |
Steps:
- Standardize dates: Convert all to
YYYY-MM-DD(ISO format).2023/12/31→2023-12-3131-12-2023→2023-12-31
- Handle missing
Amount: Impute with median amount (e.g., 750 NPR). - Fix
Merchant_ID: Standardize toMERCH123(remove underscores). - Handle missing
User_Phone: Remove the row (critical for fraud detection).
Cleaned Data:
| Transaction_ID | Amount (NPR) | Date | Merchant_ID | User_Phone |
|---|---|---|---|---|
| TXN001 | 500 | 2023-12-31 | MERCH123 | 9841234567 |
| TXN002 | 750 | 2023-12-31 | MERCH123 | 984123456 |
| TXN003 | 1200 | 2023-12-31 | MERCH123 | NULL |
Step 2: Data Integration (Combining Sources)
Definition: Merging data from multiple sources (e.g., eSewa transactions + bank records) into a unified view. Why? Business decisions need holistic data. Example: Ncell wants to analyze customer churn but needs both call logs and billing data.
Integration Techniques
| Technique | When to Use | Example |
|---|---|---|
| Union | Combine rows from similar tables | Merge eSewa payments from 2023 and 2024. |
| Join | Combine tables on a key (e.g., user_id) |
Join Daraz orders with customer profiles. |
| Intersection | Find common records | Find users active in both eSewa and Khalti. |
Worked Example: Merging Ncell and NTC Data
Goal: Analyze bus route delays vs. Ncell network drops in Kathmandu. Data Sources:
- NTC Bus GPS Logs (timestamps, location, bus ID).
- Ncell Network Tower Data (call drops, signal strength).
Steps:
- Key Alignment: Both datasets have
timestampandlocation(latitude/longitude). - Join on
location: For each bus stop, check if Ncell had drops. - Result: A new table showing delays correlated with network issues.
erDiagram
BUS_STOP ||--o{ GPS_LOG : "has"
BUS_STOP ||--o{ NETWORK_DROP : "has"
GPS_LOG {
timestamp string
bus_id string
delay_minutes int
}
NETWORK_DROP {
timestamp string
location string
drop_count int
}Step 3: Data Transformation (Structuring Data)
Definition: Converting data into forms suitable for mining. Includes:
- Aggregation (summarizing data).
- Normalization (scaling values).
- Discretization (converting continuous to categories).
Common Transformations
| Technique | Purpose | Example |
|---|---|---|
| Aggregation | Summarize data (e.g., daily → monthly) | Calculate monthly sales for Daraz. |
| Normalization | Scale data to [0,1] or [-1,1] | Normalize user ages (18–80) for clustering. |
| Discretization | Convert continuous to bins | Classify NEPSE stock prices as Low/Medium/High. |
| Encoding | Convert text to numbers | Convert Male/Female to 0/1 for ML models. |
Worked Example: Transforming NEPSE Stock Data
Raw Data:
| Date | Open (NPR) | High (NPR) | Low (NPR) | Close (NPR) |
|---|---|---|---|---|
| 2023-01-01 | 2500 | 2550 | 2480 | 2520 |
| 2023-01-02 | 2520 | 2580 | 2510 | 2560 |
Steps:
Discretize
Closeprice:Low: < 2530Medium: 2530–2570High: > 2570 →2023-01-01→Medium,2023-01-02→High.
Normalize
Volume(if available):- Original:
Volume = [1000000, 1500000] - Normalized:
(x - min) / (max - min)→1000000→0,1500000→1.
- Original:
Aggregate to weekly trends:
- Calculate
avg_close_priceper week.
- Calculate
Step 4: Data Reduction (Dimensionality Reduction)
Definition: Reducing data size or dimensions while preserving key information. Why? Large datasets slow down mining. Example: Pathao’s GPS logs have 100+ columns, but only a few affect traffic predictions.
Techniques
| Technique | When to Use | Example |
|---|---|---|
| Attribute Subset | Select most relevant features | Keep only location, timestamp, speed for Pathao. |
| Parameterization | Replace data with parameters | Replace user_purchase_history with avg_spend. |
| Numerosity Reduction | Compress data (e.g., sampling) | Sample 10% of Daraz orders instead of all. |
| Dimensionality Reduction | Use PCA/t-SNE | Reduce 50 features in NEPSE data to 5. |
Worked Example: Reducing Daraz Order Data
Original Dataset: 100 columns (user_id, product_id, price, category, reviews, etc.). Goal: Predict customer churn (will they return?).
Steps:
Attribute Subset Selection:
- Keep only:
total_spend(last 3 months)avg_order_valuedays_since_last_ordercategory_preferences(e.g., electronics vs. groceries).
- Keep only:
Numerosity Reduction:
- Original: 1M orders.
- Sample: 100K orders (randomly selected).
Result: Faster training for churn prediction models.
Real-World Applications in Nepal
| Company/App | Preprocessing Step | How It’s Used |
|---|---|---|
| eSewa | Data Cleaning | Fixes typos in merchant_id to prevent fraud. |
| Daraz | Data Integration | Merges inventory + user profiles for recommendations. |
| Ncell | Data Transformation | Converts call logs into call_duration_bins for network optimization. |
| NTC | Dimensionality Reduction | Reduces GPS logs to key traffic_jams_per_route for bus scheduling. |
| NEPSE | Aggregation | Calculates monthly_avg_stock_price for trend analysis. |
Common Pitfalls and How to Avoid Them
Over-Cleaning:
- Problem: Removing too much data (e.g., deleting all rows with missing
age). - Fix: Use imputation (fill missing values) instead of deletion.
- Problem: Removing too much data (e.g., deleting all rows with missing
Incorrect Joins:
- Problem: Joining tables on wrong keys (e.g.,
user_idvs.phone_number). - Fix: Always verify primary/foreign key relationships.
- Problem: Joining tables on wrong keys (e.g.,
Loss of Information:
- Problem: Discretizing
ageintoYoung/Middle/Agedloses granularity. - Fix: Use bin sizes wisely (e.g., 10-year ranges).
- Problem: Discretizing
Scaling Issues:
- Problem: Normalizing
price(range: 10–1,000,000) withage(18–80) distorts data. - Fix: Normalize per feature separately.
- Problem: Normalizing
Exam Tip: How This Unit is Tested
Theory Questions (30%):
- Define data cleaning, integration, transformation, and reduction.
- Explain why preprocessing is essential (use the GIGO principle).
- Compare imputation vs. deletion for missing values.
Scenario-Based Questions (40%):
- Given a dirty dataset, describe steps to clean/transform it. Example: "eSewa’s transaction data has inconsistent dates and missing amounts. How would you preprocess it?"
- Design a preprocessing pipeline for a real-world case (e.g., NEPSE stock analysis).
Practical Questions (30%):
- SQL queries to clean data (e.g.,
UPDATE,COALESCEfor missing values). - Python/Pseudocode for transformations (e.g., normalization, discretization).
- Interpretation: Given a transformed dataset, explain how it improves mining results.
- SQL queries to clean data (e.g.,
High-Scoring Answers Include:
✅ Step-by-step reasoning (e.g., "First clean missing values, then standardize dates..."). ✅ Real-world examples (tie answers to eSewa, Daraz, NEPSE, etc.). ✅ Visuals (show a preprocessing pipeline or data cleaning steps). ✅ Pros/Cons (e.g., "Imputation preserves data size but may introduce bias.").
Summary Checklist
Before mining, ensure your data is: ✔ Clean: No missing/noisy values. ✔ Integrated: Merged from all sources. ✔ Transformed: Formatted for analysis (e.g., dates as numbers). ✔ Reduced: Only essential features/rows.
Final Thought:
"Preprocessing is like preparing ingredients before cooking. Even the best chef can’t make a great dish with rotten tomatoes!" — Adapted from data mining wisdom.
Based on the TU BIT syllabus for Data Warehousing and Data Mining, unit 3.
Discussion
Loading…