2.1.14Data Preprocessing & Feature Engineering

Exploratory data analysis (EDA) workflow

3,207 words15 min readdifficulty · medium3 backlinks

The Complete EDA Workflow

The EDA workflow follows a structured path from raw data to modeling readiness:

Figure — Exploratory data analysis (EDA) workflow

Stage 1: Data Collection & Initial Inspection

WHY? You need to understand the shape, structure, and basic properties before diving deep.

WHAT to check:

  • Dimensions: number of rows (samples) and columns (features)
  • Data types: numerical, categorical, datetime, text
  • Memory usage: can it fit in RAM?
  • First/last rows: sanity check on format

HOW:

# Basic inspection commands
df.shape          # (n_rows, n_columns)
df.info()         # types, non-null counts, memory
df.head(10)       # first 10 rows
df.tail(10)       # last 10 rows
df.columns.tolist()  # feature names

Stage 2: Univariate Analysis

WHY? You must understand each variable in isolation before studying interactions.

WHAT to analyze:

For numerical variables:

  • Central tendency: mean, median, mode
  • Spread: standard deviation, IQR, range
  • Shape: skewness, kurtosis
  • Distribution: histogram, KDE plot, boxplot

Skewness=E[(Xμ)3]σ3\text{Skewness} = \frac{E[(X - \mu)^3]}{\sigma^3}

Derivation from first principles:

  • Start with the concept of moments: E[(Xμ)k]E[(X - \mu)^k] measures how data deviates from mean
  • k=1k=1: deviation (always zero by definition)
  • k=2k=2: variance σ2\sigma^2 (spread)
  • k=3k=3: raw asymetry measure
  • Divide by σ3\sigma^3 to standardize (make scale-invariant)

Skewness = 0: symmetric Skewness > 0: right tail (mean > median) Skewness < 0: left tail (mean < median)

For categorical variables:

  • Frequency counts: how many per category
  • Proportions: relative frequencies
  • Cardinality: number of unique values
  • Mode: most common category

Stage 3: Bivariate & Multivariate Analysis

WHY? Real-world patterns emerge from interactions between variables, not individual distributions.

WHAT to examine:

Numerical vs Numerical:

  • Correlation coefficient (Pearson, Spearman)
  • Scatterplots with trend lines
  • Correlation matrix heatmap

r=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2i=1n(yiyˉ)2r = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i - \bar{x})^2}\sqrt{\sum_{i=1}^{n}(y_i - \bar{y})^2}}

Derivation:

  • Start with covariance: Cov(X,Y)=E[(XμX)(YμY)]\text{Cov}(X,Y) = E[(X - \mu_X)(Y - \mu_Y)]
  • Covariance measures linear relationship but is scale-dependent
  • To make scale-invariant, divide by the product of standard deviations
  • r=Cov(X,Y)σXσYr = \frac{\text{Cov}(X,Y)}{\sigma_X \sigma_Y}
  • Ranges from -1 (perfect negative) to +1 (perfect positive)

Categorical vs Numerical:

  • Grouped boxplots (compare distributions across categories)
  • Grouped statistics (mean/median per category)
  • ANOVA F-test for significance

Categorical vs Categorical:

  • Contingency tables (crosstabs)
  • Chi-square test for independence
  • Stacked bar charts

Stage 4: Data Quality Assessment

WHY? Garbage in, garbage out. Model performance is capped by data quality.

WHAT to check:

  1. Missing values:

    • Percentage missing per column
    • Pattern of missingness: MCAR (completely random), MAR (random given other variables), MNAR (not random)
    missing_pct = (df.isnull().sum() / len(df)) * 100
    print(missing_pct[missing_pct > 0].sort_values(ascending=False))
  2. Outliers:

    • Statistical definition: beyond Q11.5×IQRQ_1 - 1.5 \times IQR or Q3+1.5×IQRQ_3 + 1.5 \times IQR
    • Z-score method: z>3|z| > 3 (more than 3 std devs from mean)
    • Domain knowledge: age = 200 years is impossible

    zi=xiμσz_i = \frac{x_i - \mu}{\sigma}

    Why Z-score? Assumes normal distribution. Derived from standardization: we measure "how many standard deviations away from mean."

  3. Duplicates:

    duplicates = df.duplicated().sum()
    df.drop_duplicates(inplace=True)
  4. Inconsistencies:

    • Categorical typos: "Male", "male", "M for same category
    • Range violations: age = -5, percentage = 150%
    • Format issues: dates as strings, mixed currency symbols

Stage 5: Hypothesis Generation

WHY? EDA should produce testable hypotheses that guide modeling and feature engineering.

WHAT to do:

  • List observed patterns
  • Form "If X, then Y" statements
  • Prioritize hypotheses by strength of evidence and business impact

Stage 6: Communication & Documentation

WHY? EDA insights are useless if not communicated to stakeholders (data scientists, product managers, executives).

WHAT to deliver:

  1. Summary report:

    • Dataset overview (size, features, target)
    • Key findings (distributions, correlations, anomalies)
    • Data quality issues and resolutions
    • Hypotheses for modeling
  2. Visualizations:

    • Annotated plots (highlight key regions)
    • Dashboard for interactive exploration
  3. Recommendations:

    • Features to engineer
    • Rows to drop/keep
    • Preprocessing steps needed
Recall ExplainDA to a 12-year-old

Imagine you're a detective who just got a box full of random puzzle pieces (your dataset). Before you start building the puzzle (machine learning model), you need to:

  1. Dump out the pieces and count them (how many rows/columns?)
  2. Sort by color and shape (univariate: what does each variable look like?)
  3. Find which pieces connect (bivariate: do age and income relate?)
  4. Notice missing or broken pieces (data quality: handle missing values, outliers)
  5. Make guesses about the final picture (hypothesis: what patterns will help?)
  6. Show your findings to teammates (communication: share visualizations)

That's EDA! You're understanding your data deeply before jumping into building models. Just like you wouldn't start a puzzle without sorting pieces first, you don't start machine learning without EDA.

Connections

  • 2.1.1-Introduction-to-data-preprocessing - EDA is the first step before cleaning
  • 2.1.15-Statistical-measuresfor-data-analysis - Statistical tools used in EDA
  • 2.1.16-Data-visualization-techniques - Visualization is core to EDA
  • 2.1.3-Handling-missing-data - Missing value handling informed by EDA
  • 2.1.5-Outlier-detection-and-treatment - Outlier detection is part of EDA
  • 2.2.1-Introduction-to-feature-engineering - EDA findings drive feature engineering
  • 2.2.8-Feature-selection-methods - EDA identifies important features
  • 3.1.1-Bias-variance-tradeoff - Sample bias discovered in EDA affects model bias

#flashcards/ai-ml

What are the six stages of the EDA workflow? :: 1) Data Collection & Loading, 2) Univariate Analysis, 3) Bivariate/Multivariate Analysis, 4) Data Quality Assessment, 5) Hypothesis Generation, 6) Communication

What is the formula for Pearson correlation coefficient?
r=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2i=1n(yiyˉ)2r = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i - \bar{x})^2}\sqrt{\sum_{i=1}^{n}(y_i - \bar{y})^2}} or equivalently r=Cov(X,Y)σXσYr = \frac{\text{Cov}(X,Y)}{\sigma_X \sigma_Y}
Why do we divide the third moment by σ3\sigma^3 to calculate skewness?
To make it scale-invariant. Raw third moment E[(Xμ)3]E[(X - \mu)^3] depends on the units of X; dividing by σ3\sigma^3 standardizes it so skewness is comparable across different scales.
What is the IQR outlier detection rule?
Outliers are values below Q11.5×IQRQ_1 - 1.5 \times IQR or above Q3+1.5×IQRQ_3 + 1.5 \times IQR, where IQR=Q3Q1IQR = Q_3 - Q_1
When does Pearson correlation fail to detect relationships?
When the relationship is non-linear. Pearson only measures linear association. A perfect parabola (Y = X²) can have r ≈ 0. Use scatterplots or Spearman rank correlation for non-linear monotonic relationships.
What are the three types of missing data patterns?
1) MCAR (Missing Completely At Random), 2) MAR (Missing At Random given other variables), 3) MNAR (Missing Not At Random - missingness depends on unobserved values)
What does positive skewness tell you about mean vs median?
Positive skewness (right tail) means mean > median. The tail pulls the mean upward while median remains resistant to outliers.
What is the difference between correlation and causation?
Correlation measures statistical association between variables. Causation means one variable directly causes changes in another. Correlation can exist due to confounding variables (both caused by a third factor) without causation.
Why use median instead of mean for imputing missing values?
Median is robust to outliers. If data has extreme values, mean gets pulled toward outliers, giving a distorted central tendency. Median represents the "typical" value better for skewed distributions.
What is multicollinearity and why does it matter?
Multicollinearity is high correlation (r > 0.8-0.9) between predictor variables. It makes regression coefficients unstable and difficult to interpret, inflates standard errors, and causes numerical issues in matrixversion.
What does a correlation matrix heatmap reveal quickly?
1) Which features are redundant (high correlation pairs), 2) Which features correlate with target variable (predictive power), 3) Multicollinearity issues for regression modeling
What is the purpose of grouped boxplots in EDA?
To compare distributions of a numerical variable across categories. Shows differences in central tendency, spread, and outliers between groups, helping identify if the categorical variable influences the numerical one.
Why create a Z-score for outlier detection?
Z-score standardizes data to "number of standard deviations from mean." Z = (x - μ)/σ. Values with |Z| > 3 are unusual (beyond 99.7% of normal distribution). Makes outlier detection scale-invariant.
What is the DUHAC mnemonic for EDA?
Dimensions, Univariate, Hypothesize, Associate, Clean - a framework for systematic exploratory data analysis workflow.
Why not automatically delete outliers?
Outliers might be: 1) Genuine extreme values (CEOs with high income), 2) Valuable edge cases for model robustness, 3) Signal in fraud/anomaly detection. Investigate with domain knowledge before deleting.

Concept Map

import & inspect

reveals shape & types

examines each variable

standardized by sigma cubed

then study pairs

via correlations

flags missing & outliers

informs stakeholders

guides

leads to

prepares data for

Raw Data

Data Collection & Loading

Univariate Analysis

Moments & Skewness

Distribution Shape

Bivariate & Multivariate Analysis

Data Quality Assessment

Hypothesis Generation

Communication

Feature Engineering

Modeling Readiness

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalo, EDA ko ek detective ki tarah samjho. Jaise doctor kisi bhi treatment se pehle patient ke vitals check karta hai, waise hi tumhe model banane se pehle apne data ko achhe se samajhna padta hai. EDA basically ek systematic process hai jisme tum visualization aur statistics ka use karke apne data se sawaal poochte ho - kya patterns hain, kya broken hai, aur kaun se assumptions safe hain. Iska core idea yahi hai ki bina data ko samjhe agar tum seedhe modeling mein kood gaye, toh baad mein hours barbaad honge debugging mein.

Workflow simple hai - pehle data load karke initial inspection karo (kitne rows-columns hain, data types kya hain, missing values kahan hain). Yeh df.shape, df.info(), aur df.head() jaise commands se hota hai jo turant reveal kar deta hai ki kahan gadbad hai. Phir univariate analysis aata hai jisme tum har variable ko akele study karte ho - numerical ke liye mean, median, standard deviation aur skewness dekhte ho, aur categorical ke liye frequency counts. Skewness ek important concept hai jo batata hai ki data symmetric hai ya kisi ek taraf jhuka hua hai - agar mean median se bada hai toh data right-skewed hai matlab kuch outliers mean ko upar kheench rahe hain.

Yeh sab important kyun hai? Kyunki EDA se hi tumhe pata chalta hai ki feature engineering mein kya karna hai. Jaise agar age right-skewed hai, toh tum log transformation apply kar sakte ho taki data model ke liye better ban jaye. Bina EDA ke tum blindly model banaoge aur galat assumptions ki wajah se results kharab aayenge. Toh yaad rakho - accha data scientist banna hai toh pehle apne data se dosti karo, uska character samjho, tabhi accha model bana paoge.

Go deeper — visual, from zero

Test yourself — Data Preprocessing & Feature Engineering

Connections