Contents/ Part IV · Preparing Data for Analysis/ Chapter 25

Exploratory Data Analysis

Before you model anything, you look. Exploratory data analysis is the open-ended, visual, skeptical first pass through a dataset: getting a feel for each variable, how they relate, and where the surprises and traps hide, so the formal analysis that follows is built on understanding, not assumptions.

⏱️ ~13 min read
🐍 Notebook included
📊 Chapter 25

Preparing Data for Analysis cleaned, reshaped, and engineered your data. This final chapter is where you actually get to know it. Exploratory data analysis (EDA) is the deliberate habit of looking at data, one variable at a time, then in pairs, then together, before committing to any model or conclusion.

🔍
Exploratory data analysis is an open-ended, mostly visual investigation of a dataset to understand its structure, summarize its main features, spot anomalies, and surface hypotheses, before formal modeling or hypothesis testing.
💬
Where the idea comes from

EDA was championed by statistician John Tukey, whose 1977 book Exploratory Data Analysis framed the analyst as a detective: the goal is to let the data speak before you impose a model on it. Tukey's enduring warning, "the greatest value of a picture is when it forces us to notice what we never expected to see," is the whole spirit of the chapter. EDA is contrasted with confirmatory data analysis (CDA), the formal testing of a pre-specified hypothesis that comes later in the book.

The two modes answer different questions, and keeping them separate matters more than it first appears:

Exploratory (EDA)Confirmatory (CDA)
"What is going on in this data?""Is this specific hypothesis supported?"
Open-ended, flexible, iterativePre-specified, disciplined, one shot
Visual and descriptiveTests, p-values, confidence intervals
Generates hypothesesEvaluates a hypothesis
⚠️
The forking-paths trap

EDA is where you hunt for patterns, but if you then run a formal test on the same data that suggested the pattern, the p-value is no longer honest, you have implicitly tried many comparisons (the "garden of forking paths"). Explore freely, but confirm on fresh data or a held-out set. This is the same leakage logic that ran through encoding and imputation in the last few chapters.

1

The EDA Workflow

A good exploration is not random clicking; it follows a rough order, from a first-contact audit of the whole table, to one variable at a time, to pairs, to everything at once.

From the whole table to the whole picture First contact shape · dtypes missing · duplicates Univariate one variable center · spread · shape Bivariate pairs of variables scatter · groups · r Multivariate many at once heatmap · pair plot each surprise sends you back to look again EDA is a loop, not a checklist: a finding at one level raises new questions at another.
🧭
Start with first contact

Before any chart, run the quick audit you have seen building all through the Preparing Data for Analysis part: df.shape, df.info(), df.describe(), df.isna().sum(), df.duplicated().sum(), and a value_counts() on key categories. It takes seconds and catches the problems, wrong dtypes, silent missingness, duplicate rows, class imbalance, that would otherwise corrupt everything downstream.

2

Univariate: One Variable at a Time

The first real exploration looks at each variable on its own and asks three questions met back in the descriptive-statistics chapters: where is its center, how much does it spread, and what is its shape?

Variable typeSummariesPlotsLook for
Numericmean, median, SD, IQR, skewHistogram, box plot, densitySkew, modality, outliers, range
Categoricalcounts, proportions, modeBar chartImbalance, rare levels, typos

For a numeric variable the histogram is the workhorse: it reveals whether the distribution is symmetric or skewed (see Shape of a Distribution), whether it has one peak or several, and whether a long tail hides outliers (see Detecting & Treating Outliers). A box plot compresses the same variable into median, quartiles, and flagged outliers, which makes it ideal for comparing groups side by side. For a categorical variable, a simple bar chart of counts exposes class imbalance and stray misspelled levels at a glance.

Petal length (cm) across 150 iris flowers setosa versicolor + virginica empty gap no flower has a 2–3 cm petal count per 0.5 cm box plot median 4.35 123 4567 petal length (cm) · the gap splits setosa (left) from the other two species (right)

The histogram (top) and box plot (bottom) describe the same column on the same axis. Two things jump out that no single number would tell you: the distribution is bimodal, with a hard empty gap from 2 to 3 cm, and that gap is not noise, it is the boundary where one species (setosa, the short-petalled cluster on the left) ends and the others begin. The box plot shows the matching wide spread (IQR 3.5 cm) and a median of 4.35 cm pulled toward the upper cluster. A hidden group inside one variable is exactly the kind of surprise EDA exists to catch.

📊
Center, spread, shape

Read the three together. A mean far from the median signals skew; a large SD or IQR signals spread; two peaks signal a mixture of groups hiding in one column. None of these show up in a single summary number, which is exactly why EDA insists you plot.

3

Bivariate & Multivariate: Relationships

Once each variable is understood alone, the interesting questions are about how they move together. The right tool depends on the pair of types.

PairPlotSummary
Numeric vs numericScatter plotCorrelation (Pearson / Spearman)
Numeric vs categoricalSide-by-side box / violinGroup means, group differences
Categorical vs categoricalGrouped bar / mosaicCross-tab, proportions
Petal length vs petal width, one dot per flower 12 34 56 7 01 2 petal length (cm) petal width (cm) setosa versicolor virginica r = 0.96 · strong, positive

The same two columns, now plotted against each other. Longer petals are reliably wider, an upward band with correlation r = 0.96. Coloring by species turns one chart into three insights at once: setosa (cyan) sits in its own tight cluster at the bottom-left, while versicolor and virginica stack along the same trend. A scatter plot reveals the shape of a relationship that a single correlation number cannot.

For two numeric variables, the scatter plot shows the shape of the relationship and a correlation coefficient puts a number on it. But correlation comes in two flavors, and choosing the wrong one quietly understates real relationships:

Pearson vs Spearman on a curved-but-rising relationship x y = x³ + noise Pearson r ≈ 0.94 measures linear association, deflated by the curve Spearman ρ ≈ 1.00 measures monotonic association on the ranks The relationship is perfectly increasing, so Spearman sees a 1.0 that Pearson, looking only for a straight line, misses.
CoefficientMeasuresUse when
Pearson rStrength of a linear relationshipThe relationship looks like a straight line; roughly symmetric data
Spearman ρStrength of a monotonic relationship (on ranks)Curved-but-rising relationships, ordinal data, or with outliers

To see many relationships at once, the correlation heatmap draws the whole correlation matrix as a grid of colors. Using a diverging palette centered at zero (red for positive, blue for negative) makes the sign and strength readable instantly, and a hot off-diagonal block flags multicollinearity: two features so correlated they carry nearly the same information (in the notebook, iris petal length and petal width sit at r ≈ 0.96).

Correlation heatmap of the four iris measurements SLSWPLPW SLSWPLPW 1.00 -0.12 0.87 0.82 -0.12 1.00 -0.43 -0.37 0.87 -0.43 1.00 0.96 0.82 -0.37 0.96 1.00 r +10−1 PL ↔ PW = 0.96 petal length & width carry nearly the same information: a multicollinearity flag SL sepal length · SW sepal width · PL petal length · PW petal width · red = positive, blue = negative

Every pair of features at a glance. The diverging scale runs blue (negative) through white (zero) to red (positive), so sign and strength read off the color instantly. The diagonal is all 1.00 (each variable with itself), and the outlined petal length × petal width cell glows at 0.96, two features so alike they are nearly redundant. That hot off-diagonal block is the visual signature of multicollinearity, a cue to drop or combine one of them before fitting a linear model (see Feature Engineering). Note too that sepal width leans slightly negative against the petal measures.

🌡️
Reading a correlation heatmap

Center the color scale at zero so positive and negative correlations are visually distinct, and fix the range to [-1, 1] so colors are comparable across plots. Scan for hot pairs of features (a multicollinearity warning that connects straight back to feature selection in Feature Engineering) and for the row matching your target (the features most linearly related to what you want to predict). Remember the limit: the heatmap only sees linear association.

4

Pitfalls & Always Plot

EDA's golden rule is the one Anscombe and the Datasaurus made unforgettable (see Charts for Numerical Data): summary statistics can lie, so always plot the data. Four datasets can share the same mean, variance, and correlation while looking completely different, one linear, one curved, one with a single outlier driving everything. Only the picture tells them apart.

🚫
Common EDA traps

Trusting a single number (a correlation or a mean) without a plot; confusing correlation with causation; reading a near-zero Pearson as "no relationship" when the link is nonlinear; and the forking-paths trap, formally testing a hypothesis the same data suggested. EDA generates ideas; it does not confirm them.

Modern tooling can accelerate the first pass. Automated profilers like ydata-profiling (once pandas-profiling), Sweetviz, and D-Tale generate a full report, distributions, missingness, correlations, warnings, from one line of code. They are a fast head start, not a replacement for looking: the human still has to ask the right questions and interpret what the report surfaces.

🤖
Why this matters, and where Preparing Data for Analysis ends

Every strong analysis and every reliable model begins with someone who genuinely understood their data first. EDA is that understanding, and it is the bridge out of data preparation: with the data cleaned (the Data-Cleaning Mindset through Feature Engineering chapters) and explored (this chapter), you are finally ready to reason about it formally. That is where the book turns next, to probability, the mathematics of uncertainty that underpins every test, model, and inference to come.

5

EDA in Machine Learning & AI

Exploratory analysis is not a warm-up you can skip, it is the first phase of every serious machine-learning project. What you learn here decides the features, the model, and the pitfalls you avoid.

What EDA checksWhy it matters for the model
Distributions & skew of each featureTells you which columns need a transform or a robust scaler before training
Correlations & feature-target relationshipsFlags redundant features to prune and promising ones to keep, and warns of leakage
Target balance & group differencesAn imbalanced target changes the metric and the training recipe you should use
🤖
EDA is where you catch leakage before it costs you

A feature that correlates suspiciously well with the target is often a leak, information that would not exist at prediction time. EDA is where you spot it, along with the class imbalance, the skew, and the missingness that shape every downstream choice. Skip it and you build on assumptions you never checked.

6

Real-World Example: Exploring a Churn Dataset

Here is a dataset built for the full EDA workflow: 500 customers with numeric columns (age, tenure, spend, tickets), a categorical plan, and a binary target, churned. A quick exploration already tells a story, overall churn is about 22%, but it climbs to 27% on the Basic plan, and it falls as tenure rises. The companion notebook runs the whole pass, profile, distributions, correlations, and churn by group.

📂 Dataset · exploratory-data-analysis-eda--customer_analytics.xlsx

One row per customer: age, tenure_months, plan, monthly_spend, support_tickets, and the target churned. The mix of numeric, categorical, and target columns is exactly what a complete exploratory pass is built to examine.

🐍

Bring it to life in Python

The companion notebook explores the classic iris dataset end to end: a first-contact audit, a univariate look at one feature (center, spread, shape with histogram and box plot), a bivariate scatter and group-by-species comparison, a correlation heatmap that exposes the petal multicollinearity, and a Pearson-vs-Spearman demo on a curved relationship that shows why you always plot.

📓 View Notebook (code & outputs) ▶ Open in Colab ⬇ View / Download on GitHub

View opens the rendered notebook instantly (no setup). Open in Colab runs & edits it live in your browser. To run locally, install numpy, pandas, scikit-learn, scipy, matplotlib and launch jupyter notebook.

🎓 Key Takeaways

  • EDA is understanding before modeling: an open-ended, visual, skeptical first pass that summarizes structure and surfaces hypotheses (Tukey, 1977).
  • Work outward: first-contact audit → univariate (center, spread, shape) → bivariate (pairs) → multivariate (all at once).
  • Pearson measures linear, Spearman measures monotonic; a near-zero Pearson does not mean "unrelated."
  • A correlation heatmap (diverging palette centered at 0) reveals strong pairs and multicollinearity, but only the linear part.
  • Always plot the data (Anscombe); and never confirm a hypothesis on the same data that suggested it (forking paths).
7

Practice Challenges

Five short challenges, beginner to intermediate. Try them on paper or in Python before checking the solutions.

1

First-contact audit

For a new DataFrame, report its shape, dtypes, total missing values, duplicate-row count, and the balance of a key category. Why run this before any chart?

Hint: shape, dtypes, isna().sum(), duplicated().sum(), value_counts().
2

Describe one variable

For a numeric column, report center (mean, median), spread (SD, IQR), and shape (skew), then draw a histogram. What does comparing mean and median tell you?

Hint: mean far from median ⇒ skew; the histogram confirms it.
3

Compare across groups

Does a numeric variable differ across a category? Compute the group means and draw side-by-side box plots. What makes a feature a good group separator?

Hint: groupby(cat)[num].mean() + boxplot per group; little overlap = strong separator.
4

Find the redundant pair

Compute a correlation matrix for several numeric features and identify the most strongly correlated pair. Why is that a multicollinearity flag?

Hint: df.corr(); the largest off-diagonal |r| is the near-duplicate pair.
5

Pearson vs Spearman

Build a monotonic but curved relationship (e.g. y = x² on positive x). Compute both correlations. Why do they differ, and what is the lesson?

Hint: Spearman (ranks) ≈ 1; Pearson is deflated by the curve, so always plot.
Check your work

A fully-worked solutions notebook walks through all five challenges in the same visual style. Try them yourself first, then compare.

📓 View Solutions ▶ Open Solutions in Colab ⬇ View / Download on GitHub
8

Quiz: Test Yourself

Eight quick questions on exploratory data analysis. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved, so you can hop back to the chapter and return anytime.