0% found this document useful (0 votes)
19 views9 pages

Data Preprocessing & EDA Guide

The document outlines the importance of data preprocessing and exploratory data analysis (EDA) in the data science lifecycle, detailing steps such as data collection, cleaning, transformation, and splitting. It also discusses types of data, tools for EDA, and techniques for handling missing values, duplicates, and outliers. Key takeaways emphasize the need for clean data, effective visualization, and proper documentation of preprocessing steps.

Uploaded by

janya Chhatwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views9 pages

Data Preprocessing & EDA Guide

The document outlines the importance of data preprocessing and exploratory data analysis (EDA) in the data science lifecycle, detailing steps such as data collection, cleaning, transformation, and splitting. It also discusses types of data, tools for EDA, and techniques for handling missing values, duplicates, and outliers. Key takeaways emphasize the need for clean data, effective visualization, and proper documentation of preprocessing steps.

Uploaded by

janya Chhatwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DATA PREPROCESSING &

EXPLORATORY DATA ANALYSIS (EDA)

SECTION 1: Role of Data Preprocessing in the Data


Science Lifecycle
🔹 Definition
Data Preprocessing is the crucial step of preparing raw data into a clean, consistent, and
usable format before applying analytical or machine learning models.

🔹 Role in Lifecycle
Step Description

1. Data Collection Gathering raw data from multiple sources.

2. Data Cleaning Handling missing, duplicate, or noisy data.

3. Data Transformation Normalizing, encoding, and scaling.

4. Data Reduction Feature selection, dimensionality


reduction.

5. Data Splitting Dividing data into training and testing sets.

🔹 Importance
●​ Increases model accuracy​

●​ Reduces bias and noise​

●​ Ensures consistency and integrity​

●​ Improves interpretability and performance​


SECTION 2: Types of Data and Their Classification
🔹 Based on Nature
Type Description Example

Structured Tabular format, rows & columns CSV, SQL tables

Unstructured No predefined structure Images, text,


audio

Semi-structure Partial structure JSON, XML files


d

🔹 Based on Measurement Scale (Statistical)


Type Description Example

Nominal Categorical without order Gender = Male/Female

Ordinal Ordered categories Education: High School < Bachelor <


Master

Interval Ordered, equal intervals, no true Temperature (°C)


zero

Ratio Ordered, equal intervals, true zero Age, Salary, Height

SECTION 3: Tools for Exploratory Data Analysis (EDA)


🔹 Purpose of Using Tools
EDA tools help visualize, summarize, and understand data before modeling.​
They enable pattern discovery, trend identification, and outlier detection.

Tool Key Features Example Use

Pandas Data handling, stats, missing [Link]()


values

NumPy Numerical computation [Link](), [Link]()

Matplotlib Basic plotting Histograms, scatter plots


Seaborn Statistical visualization [Link](),
[Link]()

Scikit-learn Preprocessing & transformation StandardScaler(),


LabelEncoder()

SECTION 4: Data Science Lifecycle – Steps


Step Description

1️⃣ Data Collection Collect data from reliable sources

2️⃣ Data Cleaning Handle missing, noisy, inconsistent


data

3️⃣ Data Preprocessing Transformation, encoding, scaling

4️⃣ EDA Explore relationships, visualize data

5️⃣ Modeling Apply ML algorithms

6️⃣ Evaluation Test model performance

7️⃣ Deployment Implement in real environment

8️⃣ Monitoring Maintain and update models

SECTION 5: Data Cleaning Essentials


🔹 Handling Missing Values
Missing Values: Data points absent in the dataset due to human error, system failure, or data
corruption.

Causes:

●​ Sensor failure​

●​ User skipped input​


●​ Data merging errors​

Methods:
Technique Description Code

Drop Missing Remove rows/columns [Link]()

Mean Imputation Replace with mean df['col'].fillna(df['col'].me


an())

Median Replace with median df['col'].fillna(df['col'].me


Imputation dian())

Mode Imputation Replace with most frequent df['col'].fillna(df['col'].mo


value de()[0])

Difference Between Mean & Median Imputation


Aspect Mean Median

Sensitive to outliers ✅ Yes ❌ No


Suitable for Normal distribution Skewed
data

SECTION 6: Data Splitting


🔹 Purpose
Dividing data into Training and Testing sets helps evaluate how well the model generalizes to
unseen data.

from sklearn.model_selection import train_test_split


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

SECTION 7: Univariate Analysis


🔹 Definition
Analyzing one variable at a time to understand its distribution, central tendency, and
dispersion.

🔹 Examples
df['Salary'].describe()
df['Gender'].value_counts()
df['Age'].hist()
[Link](x=df['Age'])

Function Purpose

describe() Summary of numerical columns

value_count Frequency of categorical data


s()

hist() Visualize distribution

boxplot() Identify outliers and spread

🔹 Example Code
df['Marks'].mean()
df['Marks'].median()
df['Marks'].hist()
[Link](df['Marks'])

SECTION 8: Normalization & Standardization


🔹 Normalization
Rescales values between 0 and 1 using Min–Max formula:​
[​
X' = \frac{X - X_{min}}{X_{max} - X_{min}}​
]

Example:

from [Link] import MinMaxScaler


scaler = MinMaxScaler()
df[['age','salary']] = scaler.fit_transform(df[['age','salary']])
🔹 Standardization
Centers data around mean = 0 and std = 1:​
[​
Z = \frac{X - \mu}{\sigma}​
]

Example:

from [Link] import StandardScaler


scaler = StandardScaler()
df[['age','salary']] = scaler.fit_transform(df[['age','salary']])

Feature Normalization Standardization

Range 0–1 Mean=0, SD=1

Sensitive to outliers Yes No

Best for Bounded data Normally distributed data

SECTION 9: Encoding Categorical Data


🔹 Label Encoding
Converts categories into numeric labels.

from [Link] import LabelEncoder


le = LabelEncoder()
df['Gender'] = le.fit_transform(df['Gender'])

⚠️ Issue: May introduce false numerical relationships.


🔹 One-Hot Encoding
Creates binary columns.

pd.get_dummies(df['City'])

Method Output Example for City = [Delhi, Mumbai, Chennai]

One-Hot Encoding Delhi → [1,0,0], Mumbai → [0,1,0], Chennai → [0,0,1]


SECTION 10: Outlier Detection
🔹 Using IQR Method
[​
IQR = Q3 - Q1​
]​
Outliers lie beyond:​
[​
Q1 - 1.5(IQR) \text{ or } Q3 + 1.5(IQR)​
]

Example:

Q1 = df['Marks'].quantile(0.25)
Q3 = df['Marks'].quantile(0.75)
IQR = Q3 - Q1
outliers = df[(df['Marks'] < Q1 - 1.5*IQR) | (df['Marks'] > Q3 + 1.5*IQR)]

🔹 Using Z-Score
If |Z| > 3, mark as outlier.

SECTION 11: Handling Duplicates


df.drop_duplicates(inplace=True)

After removing duplicates:

[Link]()

📊 Observe if mean, median, std changed — shows data accuracy improvement.

SECTION 12: EDA Visualization Toolkit


Visualization Purpose Example Code

Histogram Distribution df['Age'].hist()

Boxplot Outliers [Link](df['Salary'])

Barplot Categorical [Link](x='Dept', y='Marks',


comparison data=df)

Pairplot Relationships [Link](df)

Heatmap Correlation [Link]([Link](),


annot=True)

SECTION 13: Practical Python Snippets


Load and Explore Data
import pandas as pd
df = pd.read_csv('[Link]')
print([Link](10))

Summary Stats
df['marks'].mean(), df['marks'].median(), df['marks'].std()

Normalize All Numerical Columns


from [Link] import MinMaxScaler
scaler = MinMaxScaler()
df[df.select_dtypes('number').columns] = scaler.fit_transform(df.select_dtypes('number'))

SECTION 14: Key Takeaways


✅ Clean data = Better insights​
✅ Visualize → Understand → Transform → Model​
✅ Handle missing, duplicate, and outlier data carefully​
✅ Use correct scaling and encoding for model efficiency​
✅ Always document preprocessing steps for reproducibility

Common questions

Powered by AI

EDA is critical in the data science lifecycle because it provides a comprehensive understanding of the data before modeling. Its main goals include discovering patterns, identifying anomalies, testing hypotheses, and checking assumptions through summary statistics and visualizations . EDA facilitates the identification of data quality issues such as missing values and outliers, allowing for informed handling in subsequent preprocessing steps. It also informs feature selection and engineering, ultimately improving model performance and interpretability . By providing these insights, EDA guides the subsequent modeling steps and contributes significantly to the decision-making process in data-driven projects .

Visualization tools like Matplotlib and Seaborn are beneficial in EDA because they enable the interpretation of data through graphics, facilitating pattern recognition and the identification of trends and outliers . Matplotlib provides basic plotting capabilities suitable for quick graphic representations, while Seaborn offers enhanced statistical visualizations for deeper insights . However, limitations include the need for programming knowledge to effectively use these tools, which might be a barrier for some users. Additionally, over-reliance on visualizations without numerical backing can lead to misinterpretation of data patterns . Despite these limitations, when used appropriately, visualizations are instrumental in guiding the data analysis process and enhancing communication of findings .

Normalization rescales data to a fixed range between 0 and 1, making it suitable for algorithms requiring bounded inputs, such as neural networks. It's sensitive to outliers because they can disproportionately affect the scale of the feature . Standardization, on the other hand, centers data around a mean of 0 with a standard deviation of 1, making it appropriate for normally distributed data and methods that assume a Gaussian distribution, such as linear regression or PCA . Choosing between these methods depends on the needs of the modeling technique and the characteristics of the dataset, with normalization being ideal for scale-bound algorithms and standardization for those supporting linear relationships .

Label encoding can introduce false numerical relationships between categories, potentially leading to incorrect model interpretations. This issue arises because label encoding assigns arbitrary numerical values to categories, which might imply a rank or order that doesn't exist . To mitigate this, one-hot encoding is recommended, as it creates binary columns for each category, preserving their categorical nature without suggesting any ordinal relationship. However, one-hot encoding should be used cautiously as it increases the dimensionality of the dataset, which might lead to the curse of dimensionality in models with many categorical features .

Documenting data preprocessing steps is crucial as it ensures reproducibility, transparency, and accountability in a data science project. It allows others to understand the transformations applied to the data and reproduce the analysis or model training, which is essential for collaborative projects and future auditing . Additionally, it aids in identifying the cause of unexpected behaviors or results in models by providing a clear record of how the data was manipulated. This practice enhances the credibility of the findings and facilitates continuous improvement by making it easier to pinpoint areas for optimization .

Outlier detection and handling enhance data quality by ensuring that extreme values, which could skew analysis results or model performance, are appropriately managed. Methods for detection include the Interquartile Range (IQR) method and Z-score analysis. The IQR method identifies outliers as values lower than Q1 - 1.5*IQR or higher than Q3 + 1.5*IQR . Z-score analysis classifies data points with Z-scores above a certain threshold (typically |Z| > 3) as outliers . Properly managing outliers prevents bias in statistical analyses and model predictions, ensuring outcomes that better represent underlying trends and patterns .

Understanding data types is crucial as it dictates the analytical methods used. Structured data, like tables and CSVs, can directly utilize statistical analysis and machine learning models due to its organized format. Unstructured data, such as text or images, requires preprocessing steps like natural language processing or computer vision techniques to extract meaningful insights . Classification based on measurement scale affects analysis methods; for example, nominal data are handled with frequency analysis, ordinal data with ranking methods, interval data allow for the calculation of differences, and ratio data support all arithmetic operations . Properly distinguishing these types ensures that the chosen analysis method accurately reflects the data's characteristics and provides valid results .

Feature reduction simplifies a model by eliminating redundant or irrelevant data, which improves computational efficiency, reduces the risk of overfitting, and enhances interpretability. Common techniques include Principal Component Analysis (PCA), which transforms variables into a smaller set of uncorrelated components while retaining most of the data's variance, and feature selection methods like recursive feature elimination that iteratively removes less important features . These approaches enable models to focus on the most informative attributes, leading to more robust predictions and better generalization to new data .

Data preprocessing involves several critical steps: data cleaning, data transformation, data reduction, and data splitting. Each plays a vital role in ensuring the data's quality and suitability for analysis (1) Data cleaning involves handling missing, noisy, or duplicate data to maintain data integrity and accuracy . (2) Data transformation includes normalizing, encoding, and scaling data, which enhances model accuracy and performance by ensuring data is in a consistent format . (3) Data reduction through feature selection and dimensionality reduction simplifies the dataset, which can improve model performance and interpretability . (4) Data splitting divides the dataset into training and testing sets, enabling the evaluation of a model's generalization to unseen data . These steps collectively increase model accuracy, reduce biases, and enhance the interpretability of analytical results .

Data splitting allows for a proper evaluation of a model's ability to generalize to unseen data by dividing the dataset into training and testing sets. The training set is used to fit the model, while the testing set evaluates its performance. This separation is critical for assessing model accuracy and preventing overfitting, where a model performs well on training data but poorly on new data . Correct data splitting, often using techniques like cross-validation, ensures that the evaluation metrics reflect the model's true performance on an independent dataset, thus providing more reliable insights into its effectiveness .

You might also like