1
---
2
name: Data Cleaning Pipeline
3
description: Build robust processes for data cleaning, missing value imputation, outlier handling, and data transformation for data preprocessing, data quality, and data pipeline automation
4
---
5
6
# Data Cleaning Pipeline
7
8
## Overview
9
10
Data cleaning pipelines transform raw, messy data into clean, standardized formats suitable for analysis and modeling through systematic handling of missing values, outliers, and data quality issues.
11
12
## When to Use
13
14
- Preparing raw datasets for analysis or modeling
15
- Handling missing values and data quality issues
16
- Removing duplicates and standardizing formats
17
- Detecting and treating outliers
18
- Building automated data preprocessing workflows
19
- Ensuring data integrity and consistency
20
21
## Core Components
22
23
- **Missing Value Handling**: Imputation and removal strategies
24
- **Outlier Detection & Treatment**: Identifying and handling anomalies
25
- **Data Type Standardization**: Ensuring correct data types
26
- **Duplicate Removal**: Identifying and removing duplicates
27
- **Normalization & Scaling**: Standardizing value ranges
28
- **Text Cleaning**: Handling text data
29
30
## Cleaning Strategies
31
32
- **Deletion**: Removing rows or columns
33
- **Imputation**: Filling with mean, median, or predictive models
34
- **Transformation**: Converting between formats
35
- **Validation**: Ensuring data integrity rules
36
37
## Implementation with Python
38
39
```python
40
import pandas as pd
41
import numpy as np
42
from sklearn.preprocessing import StandardScaler, MinMaxScaler
43
from sklearn.impute import SimpleImputer, KNNImputer
44
45
# Load raw data
46
df = pd.read_csv('raw_data.csv')
47
48
# Step 1: Identify and handle missing values
49
print("Missing values:\n", df.isnull().sum())
50
51
# Strategy 1: Delete rows with critical missing values
52
df = df.dropna(subset=['customer_id', 'transaction_date'])
53
54
# Strategy 2: Impute numerical columns with median
55
imputer = SimpleImputer(strategy='median')
56
df['age'] = imputer.fit_transform(df[['age']])
57
58
# Strategy 3: Use KNN imputation for related features
59
knn_imputer = KNNImputer(n_neighbors=5)
60
numeric_cols = df.select_dtypes(include=[np.number]).columns
61
df[numeric_cols] = knn_imputer.fit_transform(df[numeric_cols])
62
63
# Strategy 4: Fill categorical with mode
64
df['category'] = df['category'].fillna(df['category'].mode()[0])
65
66
# Step 2: Handle duplicates
67
print(f"Duplicate rows: {df.duplicated().sum()}")
68
df = df.drop_duplicates()
69
70
# Duplicate on specific columns
71
df = df.drop_duplicates(subset=['customer_id', 'transaction_date'])
72
73
# Step 3: Outlier detection and handling
74
Q1 = df['amount'].quantile(0.25)
75
Q3 = df['amount'].quantile(0.75)
76
IQR = Q3 - Q1
77
lower_bound = Q1 - 1.5 * IQR
78
upper_bound = Q3 + 1.5 * IQR
79
80
# Remove outliers
81
df = df[(df['amount'] >= lower_bound) & (df['amount'] <= upper_bound)]
82
83
# Alternative: Cap outliers
84
df['amount'] = df['amount'].clip(lower=lower_bound, upper=upper_bound)
85
86
# Step 4: Data type standardization
87
df['transaction_date'] = pd.to_datetime(df['transaction_date'])
88
df['customer_id'] = df['customer_id'].astype('int64')
89
df['amount'] = pd.to_numeric(df['amount'], errors='coerce')
90
91
# Step 5: Text cleaning
92
df['name'] = df['name'].str.strip().str.lower()
93
df['name'] = df['name'].str.replace('[^a-z0-9\s]', '', regex=True)
94
95
# Step 6: Normalization and scaling
96
scaler = StandardScaler()
97
df[['age', 'income']] = scaler.fit_transform(df[['age', 'income']])
98
99
# MinMax scaling for bounded range [0, 1]
100
minmax_scaler = MinMaxScaler()
101
df[['score']] = minmax_scaler.fit_transform(df[['score']])
102
103
# Step 7: Create data quality report
104
def create_quality_report(df_original, df_cleaned):
105
report = {
106
'Original rows': len(df_original),
107
'Cleaned rows': len(df_cleaned),
108
'Rows removed': len(df_original) - len(df_cleaned),
109
'Removal percentage': ((len(df_original) - len(df_cleaned)) / len(df_original) * 100),
110
'Original missing': df_original.isnull().sum().sum(),
111
'Cleaned missing': df_cleaned.isnull().sum().sum(),
112
}
113
return pd.DataFrame(report, index=[0])
114
115
quality = create_quality_report(df, df)
116
print(quality)
117
118
# Step 8: Validation checks
119
assert df['age'].isnull().sum() == 0, "Age has missing values"
120
assert df['transaction_date'].dtype == 'datetime64[ns]', "Date not datetime"
121
assert (df['amount'] >= 0).all(), "Negative amounts detected"
122
123
print("Data cleaning pipeline completed successfully!")
124
```
125
126
## Pipeline Architecture
127
128
```python
129
class DataCleaningPipeline:
130
def __init__(self):
131
self.cleaner_steps = []
132
133
def add_step(self, func, description):
134
self.cleaner_steps.append((func, description))
135
return self
136
137
def execute(self, df):
138
for func, desc in self.cleaner_steps:
139
print(f"Executing: {desc}")
140
df = func(df)
141
return df
142
143
# Usage
144
pipeline = DataCleaningPipeline()
145
pipeline.add_step(
146
lambda df: df.dropna(subset=['customer_id']),
147
"Remove rows with missing customer_id"
148
).add_step(
149
lambda df: df.drop_duplicates(),
150
"Remove duplicate rows"
151
).add_step(
152
lambda df: df[(df['amount'] > 0) & (df['amount'] < 100000)],
153
"Filter invalid amount ranges"
154
)
155
156
df_clean = pipeline.execute(df)
157
```
158
159
## Advanced Cleaning Techniques
160
161
```python
162
# Step 9: Feature-specific cleaning
163
df['phone'] = df['phone'].str.replace(r'\D', '', regex=True) # Remove non-digits
164
165
# Step 10: Datetime handling
166
df['created_date'] = pd.to_datetime(df['created_date'], errors='coerce')
167
df['days_since_creation'] = (pd.Timestamp.now() - df['created_date']).dt.days
168
169
# Step 11: Categorical standardization
170
df['status'] = df['status'].str.lower().str.strip()
171
df['status'] = df['status'].replace({
172
'active': 'active',
173
'inactive': 'inactive',
174
'pending': 'pending',
175
})
176
177
# Step 12: Numeric constraint checking
178
df['age'] = df['age'].where((df['age'] >= 0) & (df['age'] <= 150), np.nan)
179
df['percentage'] = df['percentage'].where((df['percentage'] >= 0) & (df['percentage'] <= 100), np.nan)
180
181
# Step 13: Create data quality score
182
quality_score = {
183
'Missing %': (df.isnull().sum() / len(df) * 100).mean(),
184
'Duplicates %': (df.duplicated().sum() / len(df) * 100),
185
'Complete Features': (df.notna().sum() / len(df)).mean() * 100,
186
}
187
188
# Step 14: Generate cleaning report
189
cleaning_report = f"""
190
DATA CLEANING REPORT
191
====================
192
Rows removed: {len(df) - len(df_clean)}
193
Columns: {len(df_clean.columns)}
194
Remaining rows: {len(df_clean)}
195
Completeness: {(df_clean.notna().sum().sum() / (len(df_clean) * len(df_clean.columns)) * 100):.1f}%
196
"""
197
print(cleaning_report)
198
```
199
200
## Key Decisions
201
202
- How to handle missing values (delete vs impute)?
203
- Which outliers are legitimate business cases?
204
- What are acceptable value ranges?
205
- Which duplicates are true duplicates?
206
- How to standardize categorical values?
207
208
## Validation Steps
209
210
- Check for data type consistency
211
- Verify value ranges are reasonable
212
- Confirm no unintended data loss
213
- Document all transformations applied
214
- Create audit trail of changes
215
216
## Deliverables
217
218
- Cleaned dataset with quality metrics
219
- Data cleaning log documenting all steps
220
- Validation report confirming data integrity
221
- Before/after comparison statistics
222
- Cleaning code and pipeline documentation
223