Lecture 02: Data Preprocessing & Cleansing
Course: Introduction to Data Analytics (CE KMITL)
Lecturer: Asst. Prof. Dr. Rathachai Chawuthai, Department of Computer Engineering, Faculty of Engineering
Source Slide Deck:DA04 - Data Processing.pdf
1. Overview of Data Quality and Preprocessing
1.1 The Reality of Dirty Data
In applied machine learning and data engineering, raw data collected from physical systems, transactional databases, and human inputs is rarely clean, complete, or directly usable.
"Data cleaning is one of the three biggest problems in data warehousing."
— Ralph Kimball
Industrial surveys consistently indicate that data scientists spend between 70% to 80% of their total project time on data collection, cleansing, integration, and feature transformation.
+-------------------------------------------------------+
| Typical Distribution of Data Science Project Time |
+-------------------------------------------------------+
| [Data Cleansing & Preprocessing: ~75%] | [Model: 25%]|
+-------------------------------------------------------+
1.2 Common Sources of Data Imperfections
Data quality issues stem from three primary failure modes:
- Incomplete Data:
- Attributes with missing values (,
null, or blank cells). - Caused by equipment malfunction, voluntary survey omissions, differing data collection schemas across historical eras, or software bugs during recording.
- Attributes with missing values (,
- Noisy Data:
- Measurements containing random errors, sensor drift, or extreme variance.
- Caused by faulty instrument calibration, transmission corruption, human typographical entry errors, or optical character recognition (OCR) glitches.
- Inconsistent Data:
- Contradictory values or schema mismatches across records.
- Caused by integrating disparate databases (e.g., recording age as
"28"but birth date as"1980-01-01"), functional dependency violations, or conflicting naming conventions.
1.3 Core Data Preprocessing Tasks
To transform raw, imperfect inputs into reliable training representations, the data preprocessing phase is partitioned into five distinct sub-tasks:
2. Data Cleansing
2.1 Handling Missing Data
When datasets contain empty or unrecorded values, practitioners must select an appropriate handling strategy based on the proportion of missing data and the underlying mechanism of missingness.
Comparison of Missing Data Strategies
| Strategy | Methodology | When to Apply | Trade-offs & Risks |
|---|---|---|---|
| Ignore / Drop Tuple | Discard the entire row containing missing entries | Missingness is small () and randomly distributed | Deleting of samples discards valuable variance and induces severe selection bias |
| Manual Imputation | Domain experts manually inspect and fill each cell | Small-scale, mission-critical datasets (e.g., rare clinical trials) | High precision, but infeasible and cost-prohibitive for large-scale datasets |
| Global Constant | Fill missing values with a placeholder (e.g., "Unknown", "-999") |
Categorical variables where absence conveys distinct informational status | May distort statistical distributions if interpreted as a real numerical quantity |
| Central Tendency Imputation | Replace with feature Mean (symmetric) or Median (skewed) | Continuous numerical attributes with moderate missingness | Underestimates feature variance and artificially deflates standard deviation |
| Class-Conditional Imputation | Replace with feature mean or mode of samples sharing the same target class | Supervised classification tasks with labeled training data | Smarter than global mean; preserves class separation boundaries |
| Inference-Based Imputation | Predict missing values using regression, Decision Trees, or KNN | Features with strong correlations to other complete features | Preserves multivariate covariance structures; computationally demanding |
| Educated Guessing | Infer from surrounding related matrix responses (e.g., Likert matrix) | Survey or psychometric evaluations with repeated related scales | Relies on domain assumptions; risk of introducing confirmation bias |
2.2 Noisy Data and Outlier Detection
An outlier is an observation that deviates so substantially from other observations as to arouse suspicion that it was generated by a different mechanism.
Outlier Treatment Policy: Drop vs. Cap
- Drop: Remove the observation entirely if it represents an unambiguous measurement error, transmission glitch, or impossible physical state (e.g.,
Age = 350). - Cap (Winsorization): Replace extreme values beyond statistical thresholds with the boundary fence value itself (e.g., mapping all values to the 95th percentile value). This retains the sample count while eliminating extreme leverage.
2.3 Outlier Detection via the Interquartile Range (IQR) Fences
The Interquartile Range (IQR) is an exceptionally robust, non-parametric metric of statistical dispersion that is resilient against extreme values (unlike the sample standard deviation).
Mathematical Formulation
Given an ordered dataset partitioned into four equal quartiles:
- (First Quartile / 25th percentile): Separates the lowest 25% of data.
- (Second Quartile / Median / 50th percentile): Center of the distribution.
- (Third Quartile / 75th percentile): Separates the lowest 75% of data.
The Interquartile Range () represents the central 50% spread:
Outlier detection boundaries are defined by the Tukey Fences:
Any data point falling outside the interval is formally classified as an outlier:
(Note: In advanced exploratory diagnostics, points outside are classified as extreme outliers).
Step-by-Step Worked Numerical Example (from Lecture Deck)
Consider the following sorted dataset of 11 measurements:
- Identify Quartiles:
- The median () at index 6 is .
- Lower half: .
- Upper half: .
- Compute IQR:
- Calculate Lower and Upper Fences:
- Evaluate Outliers:
- is a lower outlier.
- is an upper outlier.
- is an upper outlier.
- Cleaned Dataset Result:
2.4 Alternative Outlier Detection Methods
- Standard Deviation Rule (Z-Score Filtering):
- Assumes a Gaussian distribution. Values with distance from mean exceeding standard deviations are flagged:
- Assumes a Gaussian distribution. Values with distance from mean exceeding standard deviations are flagged:
- Percentile Thresholding:
- Trimming or capping values outside predetermined percentiles (e.g., below the 5th percentile or above the 95th percentile).
3. Data Integration
Data integration combines data from multiple disparate sources (databases, data warehouses, flat CSV files, sensor streams) into a single, unified analytical store.
3.1 Schema Integration and the Entity Identification Problem
Real-world entities are frequently referenced using distinct column headers, keys, or conceptual representations across different corporate systems:
- Metadata Integration: Requires mapping metadata attributes, verifying data types, and reconciling disparate database keys.
- Data Value Conflicts: The same real-world entity may have contradictory attribute values due to:
- Different unit scales (Metric vs. Imperial: meters vs. feet, kilograms vs. pounds).
- Differing temporal recording snapshots (outdated address vs. updated address).
- Differing string encodings (UTF-8 vs. ASCII).
3.2 Redundancy and Correlation Analysis
Integrating multiple tables often introduces duplicate or highly correlated attributes (e.g., storing both annual_salary and monthly_salary). Redundant attributes inflate dimensionality, increase computation, and destabilize estimation in linear models.
- Continuous Features — Pearson Correlation Coefficient:
If or , one of the attributes can be pruned without loss of information.
- Categorical Features — Chi-Square () Test:
Evaluates statistical independence between categorical attributes.
4. Data Transformation & Feature Scaling
4.1 Motivation for Scaling
Continuous features naturally span widely differing numerical scales. For example:
Age: toAnnual Income: to
Algorithms whose objective functions or distance calculations compute Euclidean distance () — such as K-Means, K-Nearest Neighbors (KNN), Support Vector Machines (SVM), and Gradient Descent — will be overwhelmingly dominated by the high-magnitude income feature, rendering age mathematically negligible. Feature scaling places attributes onto comparable numerical ranges.
4.2 Min-Max Normalization
Min-Max normalization performs a linear transformation on the original data, mapping values into a fixed interval (typically ).
Formula
To rescale onto an arbitrary range :
Characteristics
- Preserves exact relative relationships among values.
- Bound within .
- Vulnerability: Highly sensitive to extreme outliers. If an outlier is introduced, all normal observations ( to ) are compressed into a near-zero range . Outliers must be handled prior to Min-Max scaling.
Worked Numerical Example (from Lecture Deck)
Given an attribute with and (range ):
| Raw Value | Normalization Step | Normalized |
|---|---|---|
4.3 Z-Score Standardization
Z-score standardization scales values based on the distribution mean () and standard deviation (). The resulting standardized distribution has zero mean () and unit variance ().
Formula
Where:
- is the arithmetic mean.
- is the standard deviation.
Characteristics
- Centers data at ; does not constrain values to a bounded interval.
- Robustness: Significantly less sensitive to outliers than Min-Max normalization because standard deviation spreads the variance across all samples.
- Highly suitable for algorithms that assume normally distributed predictors (e.g., Logistic Regression, Linear Discriminant Analysis, Principal Component Analysis).
Worked Numerical Example (from Lecture Deck)
For the dataset above with sample mean and standard deviation :
| Raw Value | Standardization Step | Standardized Score |
|---|---|---|
4.4 Normalization by Decimal Scaling
Decimal scaling normalizes by shifting the decimal point of values:
Where is the smallest positive integer such that .
Example: If values range from to , the maximum absolute value is . Setting yields , scaling the interval to .
4.5 Data Reshaping: Tidy Data vs. Sparse Matrices
- Tidy Data Principles:
- Each variable forms a distinct column.
- Each observation forms a distinct row.
- Each type of observational unit forms a distinct table.
- Sparse Matrix Representations:
When relationships across high-cardinality entities (e.g., users rating movies) contain predominantly empty interactions, storing explicit zeroes wastes memory.
- Example: User-Movie Ratings:
| User | |||||
|---|---|---|---|---|---|
- Stored compactly as coordinate tuples:
(user_id, movie_id, rating).
5. Feature Engineering
Feature engineering is the process of using domain knowledge and statistical transformations to create new features that make machine learning algorithms work more effectively.
5.1 Binning (Discretization)
Binning converts continuous numerical values or high-cardinality categorical levels into discrete bins or grouped cohorts.
- Motivation: Mitigates minor observation noise, prevents overfitting, and enhances model regularization.
- Numerical Binning Example:
- Categorical Binning Example:
5.2 Logarithmic Transformation
The logarithmic transform is among the most vital tools for stabilizing variance and handling heavily right-skewed data (e.g., personal income, transaction volume, website traffic).
Formula
(Note: is implemented as numpy.log1p(x) to safely handle non-negative features containing zero values without encountering ).
Benefits
- Reduces Positive Skewness: Compresses long right-side tails, transforming skewed distributions into near-Gaussian shapes.
- Normalizes Multiplicative Processes: In natural phenomena, absolute differences at high magnitudes (e.g., vs ) represent smaller relative impacts than at low magnitudes ( vs ). The log transform linearizes these exponential relationships.
- Diminishes Outlier Influence: Shrinks extreme values closer to the median, providing robustness to linear and distance-based estimators.
5.3 One-Hot Encoding
Machine learning models require numerical input vectors. Categorical text cannot be natively multiplied by model weights.
One-Hot Encoding maps a categorical feature with discrete categories into separate binary indicator columns containing or .
Worked Example Table (from Lecture Slide 34)
Suppose a dataset records users and their associated social network accounts:
Raw Categorical Record Table:
| User | Social Network |
|---|---|
| User A | Facebook, Twitter |
| User B | |
| User C | Instagram, Facebook |
One-Hot Encoded Binary Matrix:
| User | |||
|---|---|---|---|
| User A | |||
| User B | |||
| User C |
Pandas Implementation
import pandas as pd
# Standard single-category dummy encoding
encoded_columns = pd.get_dummies(data['social_network'])
data = data.join(encoded_columns).drop('social_network', axis=1)
(Note: In linear regression with an intercept term, one column must be omitted ( dummies) to prevent the dummy variable trap / exact multicollinearity).
5.4 Grouping Operations (Aggregations)
Transactional databases store multiple interaction rows per entity (e.g., one row per purchase). To prepare tidy feature matrices where each customer is represented by exactly one row, grouping operations are executed:
- Numerical Features: Aggregated using summary metrics:
sum(): Total lifetime customer revenue.mean(): Average transaction order value.std(): Consistency of purchasing behavior.
- Categorical Features: Aggregated using:
nunique(): Number of unique product categories purchased.mode(): Most frequently visited store location.
5.5 Feature Splitting
Deconstructing complex, compound string columns into separate, actionable features:
- Name Splitting:
"John Doe", .
- Title and Year Parsing:
"Toy Story (1995)", .- The extracted year can subsequently be used for numerical regression or binned into release decades.
5.6 Date and Time Feature Extraction
Raw date strings (e.g., "2017-01-01") are non-ordinal text strings that convey minimal direct mathematical signal to estimators if left unprocessed.
Feature Extraction Techniques
- Component Extraction: Isolating calendar attributes into separate columns:
- Year (
dt.year), Month (dt.month), Day of Month (dt.day).
- Year (
- Elapsed Time Intervals: Computing dynamic durations relative to reference benchmarks:
- Elapsed years: .
- Elapsed months: .
- Cyclical and Behavioral Flags:
- Day of week name (
dt.day_name())Monday,Sunday. - Weekend indicator: .
- Seasonal indicators: Quarter, holiday indicator.
- Day of week name (
Python Code Implementation (from Lecture Slide 44)
from datetime import date
import pandas as pd
# Sample date DataFrame
data = pd.DataFrame({'date': [
'01-01-2017',
'04-12-2008',
'23-06-1988',
'25-08-1999',
'20-02-1993'
]})
# 1. Transform string to datetime object
data['date'] = pd.to_datetime(data['date'], format="%d-%m-%Y")
# 2. Extract calendar year and month
data['year'] = data['date'].dt.year
data['month'] = data['date'].dt.month
# 3. Compute elapsed years and elapsed months from current reference
current_year = date.today().year
current_month = date.today().month
data['diff_years'] = current_year - data['date'].dt.year
data['diff_months'] = (current_year - data['date'].dt.year) * 12 + (current_month - data['date'].dt.month)
# 4. Extract weekday name
data['day_name'] = data['date'].dt.day_name()
Output Feature Table
| Date | Year | Month | Diff Years | Diff Months | Day Name |
|---|---|---|---|---|---|
2017-01-01 |
Sunday | ||||
2008-12-04 |
Thursday | ||||
1988-06-23 |
Thursday | ||||
1999-08-25 |
Wednesday | ||||
1993-02-20 |
Saturday |
6. Chained Processing Pipelines and Data Dictionaries
In production environments, data preprocessing operations are chained into reproducible, modular DAGs (Directed Acyclic Graphs).
6.1 Modular Pipeline Architecture
6.2 Data Dictionary Documentation Standard
To maintain data governance across pipeline stages, every generated intermediate dataset () requires a formal Data Dictionary specification:
- Dataset Identifier:
dx2_UserSocialMedia - File System Target:
/var/system/XYZ/dataset/dx2_{YYYY-MM-DD}.csv - Generation Schedule: Daily batch execution at 02:00 UTC.
- Schema Specification:
| Field Name | Data Type | Permissible Values | Description / Semantics |
|---|---|---|---|
user_id |
String | Alphanumeric (e.g., U1042) |
Unique primary key identifying the user account |
facebook |
Boolean / Int | Binary flag indicating connected Facebook account | |
instagram |
Boolean / Int | Binary flag indicating connected Instagram account | |
twitter |
Boolean / Int | Binary flag indicating connected Twitter account |
7. Chapter Summary & Best Practices Checklist
- Cleansing First: Detect and resolve missing values and outliers before applying feature scaling.
- Outlier Fences: Use with fences for non-parametric outlier filtering.
- Normalization vs. Standardization:
- Use Min-Max () when absolute bounded ranges are required and extreme outliers have been removed.
- Use Z-Score () when preserving variance and minimizing vulnerability to extreme values is paramount.
- Log Transformation: Apply to right-skewed positive features to compress heavy tails and normalize variance.
- Categorical Encodings: Convert categorical strings to binary vectors using One-Hot Encoding, while avoiding multicollinearity in linear models.
- Date Deconstruction: Decompose raw timestamp strings into years, months, weekdays, and elapsed duration intervals.