Sub topic 12
Pitfalls: overreading patterns and leaking information
This chapter assumes you can load and clean a DataFrame, draw histograms and box plots with matplotlib, and read basic summary statistics. It follows the bivariate analysis chapter. Here you learn to spot the mistakes that most often turn a tidy-looking EDA into a misleading one.
An EDA is meant to produce hypotheses. The pitfalls below all come from treating an exploratory observation as a proven fact, or from letting information into the analysis that should not be there.
Why these pitfalls matter
Exploration is flexible by design. You try many plots, many subsets, and many variable pairs. Each choice is reasonable, but together they give chance many opportunities to look like a pattern. Later modeling or reporting then inherits that pattern as if it were established.
There are two broad families of problems:
- Overreading: seeing structure in the data that is noise, a side effect of how you sliced it, or a result of a confounder.
- Leaking: using information in the analysis that would not be available in the real setting, or that lets test data influence your decisions.
Overreading: multiple comparisons
If you test 20 unrelated variable pairs, you should expect about one to look "significant" at the 5% level by chance alone. In EDA you rarely count how many pairs you looked at, so the one striking plot gets remembered and the other 19 are forgotten.
The effect is easy to demonstrate with pure noise. The code below builds 40 random columns and one random target, then finds the strongest correlation.
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
noise = pd.DataFrame(rng.normal(size=(100, 40)),
columns=[f"x{i}" for i in range(40)])
target = pd.Series(rng.normal(size=100), name="y")
corrs = noise.corrwith(target).abs().sort_values(ascending=False)
print(corrs.head(3).round(2))Every column is independent of the target, yet the strongest correlation usually lands around 0.25 to 0.3 with 100 rows. In a notebook, that would look like a lead worth chasing.
Practical habits:
- Keep a count of how many comparisons you made, and write it in your findings log.
- Treat a pattern found after many looks as a hypothesis, not a result.
- Check whether the pattern holds on data you did not use to find it (see the leakage section).
Overreading: small groups
Group statistics on a handful of rows are unstable. A region with 6 orders can show the highest average amount simply because one large order landed there.
Always print group sizes next to group statistics:
summary = (
df.groupby("region")["amount"]
.agg(n="size", mean="mean", median="median")
.sort_values("mean", ascending=False)
)
print(summary)If the top group has a small n, say so in the finding, or merge it with other groups before drawing a conclusion. A box plot hides group size too, so add the counts to the tick labels when groups differ a lot in size.
Overreading: correlation, confounders, and Simpson's paradox
A correlation between two columns says they move together in this sample. It does not say one causes the other. A third variable, called a confounder, may drive both. In the orders data, discount level and order amount might correlate only because large business customers both receive discounts and place large orders.
Simpson's paradox is the extreme case. A trend that appears in the combined data reverses once you split by a third variable. The following example builds a small table where the overall trend and the within-group trend disagree.
import pandas as pd
data = pd.DataFrame({
"segment": ["small"] * 6 + ["large"] * 6,
"discount": [0, 0, 0, 5, 5, 5, 10, 10, 10, 15, 15, 15],
"amount": [50, 52, 54, 55, 57, 59, 200, 202, 204, 205, 207, 209],
})
print("overall correlation:", round(data["discount"].corr(data["amount"]), 2))
for name, g in data.groupby("segment"):
print(name, round(g["discount"].corr(g["amount"]), 2))Here both trends are positive, so the data does not show a reversal. Change the pattern so that, within each segment, higher discounts go with lower amounts, while the large segment has both higher discounts and higher amounts. The overall correlation then stays positive while each within-segment correlation turns negative. That reversal is the paradox. The lesson holds either way: check a relationship inside the main subgroups before you report it for the whole dataset.
Overreading: choosing the story after the plot
Another trap is adjusting bins, axis limits, or filters until a pattern appears, then reporting only that view. Histogram bin count changes the apparent shape of a distribution. A truncated y-axis exaggerates differences between bars.
Guidelines:
- Try at least two bin widths before calling a distribution bimodal.
- Start bar charts at zero.
- Record any filter you applied before a plot, such as "excluding orders over 5,000", in the markdown cell next to it.
Leaking information
Leakage means the analysis uses information it should not. Even if you never train a model, EDA often feeds a later modeling step, and the decisions you make during exploration (which features look good, what to cap, what to drop) carry over.
Target leakage
A column is a target leak if it is recorded after, or as a consequence of, the outcome you want to predict. Suppose you want to predict whether an order will be refunded. A column such as refund_amount or refund_date is only filled in after a refund happens. It will look like a perfect predictor in EDA, and it will be useless at prediction time.
Signs of a leak:
- A feature that is almost perfectly associated with the target.
- A column that is missing exactly when the target has one value.
- A column whose name or documentation describes an event that happens after the outcome.
A quick check is to compare missingness against the target:
leak_check = (
df.assign(is_refunded=df["refund_date"].notna())
.groupby("is_refunded")["refund_amount"]
.apply(lambda s: s.notna().mean())
)
print(leak_check)If the share of non-missing refund_amount is 0 for one group and 1 for the other, the column encodes the outcome.
Letting all rows shape your decisions
When you plan to build a model or report a held-out result, the evaluation data must stay unseen. If you compute statistics on the whole dataset and use them to choose cleaning rules, outlier caps, category groupings, or features, information from the evaluation rows has already influenced the pipeline.
A safer order of work:
- Split off a test set early, before detailed exploration. Use a fixed seed from your setup cell.
- Explore and make decisions using only the training portion.
- Apply the same rules to the test portion without refitting them.
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.2, random_state=SEED)
train = train.copy()
cap = train["amount"].quantile(0.99)
train["amount_capped"] = train["amount"].clip(upper=cap)
test = test.assign(amount_capped=test["amount"].clip(upper=cap))The cap comes from the training rows only, and the same value is applied to the test rows. If you computed the 99th percentile on all of df, the test set would have influenced the rule.
Time leakage
For data with dates, a random split can place future rows in training and past rows in test. A model, or a conclusion, then benefits from information that would not exist at the time of prediction. Split by time instead: earlier orders for training, later orders for testing. Also be careful with features computed over the whole history, such as "customer's total number of orders", which include orders after the one you are describing.
cutoff = df["order_date"].quantile(0.8)
train = df[df["order_date"] <= cutoff]
test = df[df["order_date"] > cutoff]Duplicates and group leakage
If the same customer appears many times, a random split puts some of their orders in training and some in test. The test then rewards memorizing customers. When rows belong to groups, split by group. The duplicate audit from the data quality chapter helps here, because near-duplicate rows cause the same problem.
A pitfall checklist for your notebook
| Question to ask | Pitfall it catches |
|---|---|
| How many pairs or subsets did I look at? | Multiple comparisons |
| What is the group size behind each statistic? | Small groups |
| Does the pattern hold inside major subgroups? | Simpson's paradox, confounders |
| Would this column exist at prediction time? | Target leakage |
| Which rows did I use to choose this rule? | Test data influencing decisions |
| Did I split by time or by group where needed? | Time and group leakage |
Add a short section near the end of the notebook, or entries in the findings log, that answers these questions for the findings you plan to report.
Common errors
- Reporting the best of many plots without saying how many you made.
- Quoting a group mean without its size.
- Treating a high correlation as proof of a mechanism.
- Computing means, caps, or encodings on the full dataset and then splitting.
- Keeping an after-the-fact column because it "improves" the plot.
- Looking at the test set "just once" during EDA.
Exercise
You find that discount_pct has a correlation of 0.31 with amount after checking 35 other column pairs, and the effect disappears within each customer segment. Name two pitfalls this could illustrate and one step you would take before reporting it.
Show answer
The result could reflect multiple comparisons (with 36 pairs, a correlation of this size can appear by chance) and a confounder or Simpson's paradox (customer segment drives both discount and amount, so the pattern vanishes within segments). Before reporting, record it in the findings log as a hypothesis, state that 36 comparisons were made, and show the correlation within each segment. A check on held-out training/test data would also help.
Exercise
A teammate computes the 99th percentile of amount on the full DataFrame, uses it to cap outliers, and then splits into train and test. What is wrong, and how do you fix it?
Show answer
The cap was computed with test rows included, so test data influenced a cleaning rule. Split first, compute the percentile on the training set only, and apply that same value to both sets.