Sub topic 3
Exploring the Data Before Modeling
Exploratory data analysis (EDA) is the step between collecting data and cleaning it. You look at the data to learn its shape, its problems, and its relationship to the target. This chapter assumes you know basic pandas (selecting columns, groupby), basic statistics (mean, variance, distributions), and that you have already framed the problem and chosen a target column.
EDA is not about producing charts. Its purpose is to find facts that change what you do next: which columns to clean, which to drop, which splits to use, and which metrics make sense.
What EDA should answer
Before you model, try to answer these questions:
- How many rows and columns are there, and what does one row represent?
- What type is each column, and does that type match its meaning?
- How much is missing, and is it missing at random?
- How is the target distributed?
- Which features look related to the target, and which look suspiciously related?
- Are there duplicates, impossible values, or extreme outliers?
Keep notes as you go. Each finding should lead to a decision in the cleaning or feature steps.
A first pass: structure and types
Start with the cheapest checks. The code below runs on a built-in dataset, so you can run it as shown.
import pandas as pd
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
df = X.copy()
df["target"] = y
print(df.shape)
print(df.dtypes.value_counts())
print(df.isna().sum().sum(), "missing cells")
print(df.duplicated().sum(), "duplicate rows")
print(df.describe().T[["mean", "std", "min", "max"]].head(8))Read the output carefully. Look at shape to confirm the row count matches what you expect. Check dtypes for numbers stored as text or dates stored as strings. In describe, compare min and max to what is physically possible. An age of -1 or a price of 0 usually signals a placeholder value, not a real measurement.
Common type errors
| Symptom | Likely cause | Action |
|---|---|---|
| Numeric column has dtype `object` | A stray string such as "N/A" or "?" | Convert with `pd.to_numeric(errors="coerce")`, then treat the new NaNs as missing |
| ID column looks numeric | Identifiers are labels, not quantities | Exclude from features |
| Category stored as integers | Codes such as 1, 2, 3 | Treat as categorical, not numeric |
| Date stored as string | Loaded from CSV | Parse with `pd.to_datetime` |
Examine the target first
The target distribution shapes everything downstream. For classification, check class balance. For regression, check skew and range.
counts = df["target"].value_counts()
print(counts)
print(df["target"].value_counts(normalize=True).round(3))In this dataset, about 63% of rows belong to one class. That is mildly imbalanced. It tells you three things:
- Use a stratified split so each split keeps the same class ratio.
- Accuracy alone is a weak metric, because always predicting the majority class already scores about 63%.
- A baseline model has a number to beat.
With heavy imbalance, such as 1% positives, these effects get much stronger. Plain accuracy becomes almost meaningless.
For a regression target, plot a histogram. A long right tail (as with prices or incomes) often suggests a log transform of the target or a metric that is less sensitive to large errors.
Look at each feature alone
Univariate analysis means examining one column at a time. For numeric columns, check the range, the spread, and the shape. For categorical columns, check the number of distinct values and how rare the rare ones are.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 3))
df["mean radius"].hist(bins=30, ax=axes[0])
axes[0].set_title("mean radius")
df["mean area"].hist(bins=30, ax=axes[1])
axes[1].set_title("mean area")
plt.tight_layout()
plt.show()
print(df[["mean radius", "mean area"]].skew())Things to look for:
- Skew. A strongly skewed feature (skew well above 1) may benefit from a log or power transform for linear models. Tree-based models do not care.
- Scale differences. Mean area here is in the hundreds to thousands, while other features are below 1. Scale-sensitive models such as logistic regression and k-nearest neighbors need scaling.
- Constant or near-constant columns. They carry no information.
- High-cardinality categories. A column with thousands of distinct values makes one-hot encoding expensive and sparse.
Look at features against the target
Bivariate analysis compares a feature with the target. For a classification problem, compare the feature's distribution across classes.
print(df.groupby("target")[["mean radius", "mean texture", "mean smoothness"]].mean().round(3))
corr = df.drop(columns="target").corrwith(df["target"]).sort_values()
print(corr.head(5))
print(corr.tail(5))A large difference in group means, or a strong correlation with the target, marks a feature that is probably useful. Correlation measures only linear association, so a weak value does not prove a feature is useless. A feature can have a strong nonlinear relationship and near-zero correlation.
Too good to be true
If one feature predicts the target almost perfectly, do not celebrate yet. Ask how that value would be known at prediction time. A column such as "refund issued" in a churn dataset, or "discharge status" in a hospital readmission dataset, may be recorded after the outcome. That is data leakage, and a later chapter covers it in detail. EDA is where you first catch it, by noticing a correlation that is implausibly strong.
Look at features against each other
Correlated features are redundant. Check the pairwise correlation among inputs.
import numpy as np
feature_corr = df.drop(columns="target").corr().abs()
upper = feature_corr.where(np.triu(np.ones(feature_corr.shape, dtype=bool), k=1))
pairs = upper.stack().sort_values(ascending=False)
print(pairs.head(5))In this dataset, "mean radius", "mean perimeter", and "mean area" are nearly collinear, since all three measure the size of the same object. Collinearity does not hurt the predictions of most models much. It does make linear coefficients unstable and hard to interpret. Note it now. You can decide later whether to drop columns, regularize, or accept it.
Missing values: pattern, not just count
Counting missing cells is not enough. The reason a value is missing affects how to handle it.
- Missing completely at random: the gap has no relation to any data. Simple imputation is usually safe.
- Missing at random: the gap depends on other observed columns. Imputing using those columns can help.
- Missing not at random: the gap depends on the missing value itself, such as high earners skipping an income question. Imputation can bias results, and the missingness itself may be informative.
Check whether missingness relates to the target:
demo = pd.DataFrame({
"income": [50, None, 70, None, 90, 60, None, 80],
"target": [0, 1, 0, 1, 0, 0, 1, 0],
})
print(demo.assign(missing=demo["income"].isna()).groupby("missing")["target"].mean())Here, rows with missing income have a target rate of 1.0, against 0.0 for the rest. That pattern suggests adding a "was missing" indicator feature. This is why you inspect before you impute.
Outliers
An outlier is a value far from the bulk of the data. Detect with the interquartile range (IQR) rule: values beyond 1.5 times the IQR from the quartiles.
q1, q3 = df["mean area"].quantile([0.25, 0.75])
iqr = q3 - q1
mask = (df["mean area"] < q1 - 1.5 * iqr) | (df["mean area"] > q3 + 1.5 * iqr)
print(mask.sum(), "flagged rows")Flagging is not deleting. Decide for each case:
- A data entry error (a height of 1,800 cm): fix or set to missing.
- A real but rare value: keep it. These often matter most, such as large fraudulent transactions.
- A value that would not occur in production: consider excluding it, and document why.
Keep EDA honest about the test set
Exploration can leak information too. If you study the whole dataset, then pick features or thresholds because of what you saw, the test set has influenced your choices. The safe habit is to split first, then explore the training portion only. Quick checks of shape, types, and target balance on the full data are harmless. Decisions based on feature-target relationships should come from training rows.
Common mistakes
- Skipping the target check, then reporting accuracy on an imbalanced problem.
- Trusting
describe()alone. Means hide bimodal data and outliers. - Deleting outliers without checking whether they are real.
- Using the full dataset to pick features, which leaks test information.
- Treating strong correlation as causation or as proof of usefulness.
- Producing many plots and recording no decisions.
Exercise
A dataset has a target where 97% of rows are class 0. A colleague reports 97% accuracy for a model and calls it excellent. Using what EDA showed you, what is wrong, and what two changes would you make?
Show answer
A model that always predicts class 0 would also score 97%, so the accuracy says nothing about whether the model learned anything. First, use metrics that reflect the minority class, such as precision, recall, or F1, and compare against a majority-class baseline. Second, use a stratified split so train and test sets keep the same class ratio.
Exercise
A numeric-looking column "zip_code" has a correlation of 0.02 with the target. Should you conclude it is useless, and how should you treat it?
Show answer
No. Zip codes are identifiers for categories, so a linear correlation of their numeric values is meaningless. Treat the column as categorical, check its cardinality, and compare the target rate across groups before deciding whether to encode or drop it.