The one-line mental model
Exploratory data analysis is a disciplined argument: profile what you have, clean what is broken with documented decisions, then test each claim against a distribution, a correlation, or a segment comparison before you write it down as an insight.
You will be able to:
- Run a repeatable audit of shape, dtypes, nulls, and duplicates
- Choose column-aware cleaning strategies and log every transformation
- Profile single columns and pairs with the right chart for each type
- Convert observations into quantified, caveat-bearing insights
Prerequisites
- !Pandas indexing and dtypes
- !Matplotlib or Seaborn basics
- !Mean, median, standard deviation, and correlation
What You'll Learn
- 1Structure an EDA notebook so a reviewer can re-run it top to bottom
- 2Quantify missingness and decide drop versus impute per column
- 3Read histograms, boxplots, and heatmaps for skew, outliers, and collinearity
- 4Write an insight summary that states evidence and limits, not just conclusions
What EDA is for â and what it is not
EDA exists to de-risk everything that comes after it: feature engineering, modeling, pricing decisions. The deliverable is not a gallery of charts; it is a written record of what the dataset can and cannot support. A correlation of 0.8 between two columns in a sample of forty rows is an anecdote. A conversion difference that survives a segment breakdown across three weeks is a finding.
Work in a copy of the raw table and never mutate the original in place. Every notebook should be re-runnable from a clean kernel â if running cells out of order changes your answer, the analysis is not reproducible and cannot be trusted in review.
The audit: what am I actually holding?
Start with structure before statistics. Shape, column types, null counts, duplicate keys, and constant columns take about ten lines of code and prevent an entire class of downstream surprises â a target column stored as strings, an ID column that is not unique, a feature that is 97% one value.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("data/online_retail.csv", parse_dates=["invoice_date"])
def audit_frame(df: pd.DataFrame) -> pd.DataFrame:
report = pd.DataFrame({
"dtype": df.dtypes.astype(str),
"non_null": df.notna().sum(),
"nulls": df.isna().sum(),
"null_pct": (df.isna().mean() * 100).round(2),
"n_unique": df.nunique(dropna=True),
})
report["constant"] = report["n_unique"] <= 1
return report.sort_values("null_pct", ascending=False)
print(f"Shape: {df.shape[0]:,} rows x {df.shape[1]} columns")
print(audit_frame(df))
print(f"Fully duplicate rows: {df.duplicated().sum():,}")
key_cols = ["invoice_no", "stock_code"]
dups = df.duplicated(subset=key_cols).sum()
print(f"Duplicates on {key_cols}: {dups:,}")
Read the audit out loud to yourself: which columns would you refuse to feed a model today, and why? That list becomes the cleaning plan.
Cleaning with decisions on the record
Blind dropna can delete half a dataset; blind fillna(0) invents data. The honest approach is per-column, driven by how the null likely arose, and recorded so a reviewer can challenge the choice later. Keep a simple log â column, action, rows affected â because that log is what turns a notebook into an auditable analysis.
cleaning_log = []
def log(col, action, rows_affected):
cleaning_log.append({
"column": col, "action": action, "rows_affected": rows_affected
})
before = len(df)
df = df.drop_duplicates(subset=key_cols, keep="first")
log("invoice_no+stock_code", "drop_duplicates", before - len(df))
before = len(df)
df = df[df["quantity"] > 0]
df = df[df["unit_price"] > 0]
log("quantity/price sign filter", "drop_negative", before - len(df))
before = len(df)
df = df.dropna(subset=["customer_id"])
log("customer_id", "dropna_subset", before - len(df))
df["country"] = df["country"].fillna("Unknown")
log("country", "fill_unknown", 0)
df["revenue"] = df["quantity"] * df["unit_price"]
print(pd.DataFrame(cleaning_log))
print(f"Rows retained: {len(df) / before:.1%} of post-audit data")
Watch the retained-row percentage. If cleaning leaves you with 30% of the original rows, the remaining analysis is conditional on that subset and every insight must say so. That is not a reason to skip cleaning â it is a reason to state the population your numbers describe.
Profiling one column at a time
Numeric columns want three views together: a histogram for shape, a boxplot for outliers, and a quantile table for robustness. Categorical columns want counts, percentages, and a long-tail check. Time columns want an index-ordered line so gaps and regime changes are visible.
sns.set_style("whitegrid")
def profile_numeric(df, col):
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
sns.histplot(df[col].dropna(), bins=40, kde=True, ax=axes[0])
axes[0].set_title(f"{col} distribution")
sns.boxplot(x=df[col], ax=axes[1])
axes[1].set_title(f"{col} boxplot")
skew = df[col].skew()
kurt = df[col].kurtosis()
stats = df[col].describe(percentiles=[0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99])
axes[2].axis("off")
axes[2].text(0, 0.5, f"skew={skew:.2f}\nkurtosis={kurt:.2f}\n\n{stats}",
family="monospace", va="top")
plt.tight_layout()
plt.show()
profile_numeric(df, "revenue")
vc = df["country"].value_counts()
share = (vc / vc.sum() * 100).round(1)
print(pd.DataFrame({"count": vc, "share_pct": share}).head(12))
print(f"Categories covering 90% of rows: "
f"{(share.cumsum() <= 90).sum() + 1} of {len(vc)}")
A practical rule: if one or two categories cover nearly all rows, model them as-is and bucket the tail; if the distribution is flat, one-hot encoding will explode your feature space and you need target or frequency encoding instead.
Relationships: pairs, segments, and confounders
Univariate profiling finds broken columns; bivariate analysis finds stories. Correlation heatmaps surface collinearity and candidate targets, boxplots compare a numeric outcome across categories, and segment tables expose Simpson's-paradox style reversals before they embarrass you in a review.
num_cols = df.select_dtypes(include=[np.number]).columns
plt.figure(figsize=(10, 8))
corr = df[num_cols].corr(method="spearman")
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", center=0,
square=True, cbar_kws={"shrink": 0.8})
plt.title("Spearman correlation (rank-based, robust to outliers)")
plt.tight_layout()
plt.show()
def segment_comparison(df, value_col, segment_col, top_n=6):
top = df[segment_col].value_counts().head(top_n).index
subset = df[df[segment_col].isin(top)]
stats = subset.groupby(segment_col)[value_col].agg(
n="count", median="median", mean="mean",
p90=lambda s: s.quantile(0.90),
).round(2)
print(stats.sort_values("median", ascending=False))
segment_comparison(df, "revenue", "country")
groups = [g["revenue"].dropna() for _, g in df.groupby("country")
if len(g) >= 30]
from scipy import stats as scipy_stats
stat, p = scipy_stats.kruskal(*groups)
print(f"Kruskal-Wallis across countries: p={p:.4f}")
Spearman instead of Pearson is a deliberate choice for retail-like data: revenue is heavy-tailed, and rank correlation is far less sensitive to a handful of enormous invoices. Note it in the write-up so the next reader knows you did not flip methods until something looked significant.
From observations to insights you can defend
An insight is not a number that looks interesting â it is a pattern that survives contact with alternative explanations. The difference matters because the first thing a skeptical reviewer (or a hostile stakeholder) will do is ask whether the pattern could be an artifact of how you cleaned the data, how you defined the segments, or which subset you happened to examine. Defensible insights have a trail: the audit showed the data was representative, the cleaning decisions are logged, the segment definitions are explicit, and the effect is large enough to matter operationally.
Write each insight as a claim-evidence-consequence triple. The claim is the finding itself; the evidence is the specific chart, table, or statistic that supports it; the consequence is the action or decision it implies. This structure forces you to connect the analysis to something a product manager, marketer, or engineer would actually do differently â and if no such action exists, the insight is probably not worth the slide it lives on. Keep a running list of "questions we could not answer" alongside the findings; that honesty section is what separates a rigorous EDA from a decorative one.
An insight has three parts: the claim, the evidence, and the boundary. "Weekend revenue per invoice is 18% higher than weekday (median 42.1 vs 35.7, Mann-Whitney p under 0.01, weekends n=1,840 invoices) â but the gap is concentrated in the two largest markets and disappears in the long tail of small countries." The third clause is what makes it usable; without it the number will be misapplied.
df["weekday"] = df["invoice_date"].dt.dayofweek
df["is_weekend"] = df["weekday"] >= 5
comparison = df.groupby("is_weekend")["revenue"].agg(
invoices="count",
median_revenue="median",
mean_revenue="mean",
).round(2)
print(comparison)
weekend = df.loc[df["is_weekend"], "revenue"]
weekday = df.loc[~df["is_weekend"], "revenue"]
stat, p = scipy_stats.mannwhitneyu(weekend, weekday, alternative="two-sided")
median_gap = weekend.median() / weekday.median() - 1
print(f"Median gap: {median_gap:+.1%}, Mann-Whitney p={p:.4f}")
for region, sub in df.groupby("region"):
if len(sub) < 200:
continue
w_end = sub.loc[sub["is_weekend"], "revenue"].median()
w_day = sub.loc[~sub["is_weekend"], "revenue"].median()
print(f" {region}: weekend vs weekday median {w_end:.1f} vs {w_day:.1f}")
Deliver the project as a short written summary plus the notebook: three to five quantified insights, the cleaning decisions you made and why, and a list of questions the dataset cannot answer. That list of open questions is often the most valuable output of an EDA, because it tells the business what instrumentation or sampling is missing before the next modeling cycle.