27. Exploratory data analysis — Cheat sheet
The essentials of module 27 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| summarize all numeric columns | df.describe() |
df.describe().T (one row per column) |
get extra quantiles in describe |
percentiles=[...] |
s.describe(percentiles=[0.01, 0.99]) |
| get any quantiles | s.quantile([...]) |
s.quantile([0.1, 0.5, 0.9]) |
| measure lopsidedness | s.skew() |
> 1: strongly right-skewed |
| shares of each category | value_counts(normalize=True) |
df["plan"].value_counts(normalize=True) |
| include missing values in counts | dropna=False |
s.value_counts(dropna=False) |
| count the levels | nunique() |
df.select_dtypes("str").nunique() |
| check the target balance | shares of the target | df["churned"].value_counts(normalize=True) |
| linear association of two columns | Pearson | s.corr(t) |
| monotonic association, less sensitive to outliers | Spearman | s.corr(t, method="spearman") |
| correlation matrix of a table | df.corr(...) |
df.corr(method="spearman", numeric_only=True) |
| correlate every column with one Series | corrwith |
df[cols].corrwith(df["churned"]) |
| rank by strength, keep the sign | key=abs |
rho.sort_values(key=abs, ascending=False) |
| compare a number across groups | groupby().agg() |
df.groupby("g")["x"].agg(["size", "median"]) |
| rate of a 0/1 target per group | mean of the target | df.groupby("contract")["churned"].mean() |
| rate per bin of a number | pd.cut + groupby |
df.groupby(pd.cut(df["age"], bins), observed=True) |
| outcome rate per group, as a table | crosstab(..., normalize="index") |
pd.crosstab(df["contract"], df["churned"], normalize="index") |
| add totals to a crosstab | margins=True |
pd.crosstab(a, b, margins=True) |
| value for each pair of two categories | pivot_table |
df.pivot_table(index="a", columns="b", values="y", aggfunc="mean") |
| top and bottom cell of a pivot | stack() + idxmax() |
pivot.stack().idxmax() |
| list each pair of a matrix once | upper triangle | m.where(np.triu(np.ones(m.shape, dtype=bool), k=1)).stack().dropna() |
| check a trend inside groups | groupby().apply |
df.groupby("g")[[x, y]].apply(lambda d: d[x].corr(d[y])) |
| merge rare high counts | clip(upper=...) |
s.clip(upper=5) |
| check a key | is_unique, duplicated |
df["id"].is_unique |
Variable type → tool
Section titled “Variable type → tool”| Type | One column | With a numeric column | With a categorical column |
|---|---|---|---|
| Numeric | describe, quantile, skew, histogram |
scatter, Pearson, Spearman | groupby().agg(), box plot per group |
| Categorical | value_counts(normalize=True), nunique |
groupby().agg() |
crosstab(normalize=...) |
| Binary target (0/1) | mean() = rate |
pd.cut + mean of target |
mean of target per group, lift |
Univariate: numeric
Section titled “Univariate: numeric”import numpy as npimport pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
houses = pd.read_csv("data/houses.csv")price_k = houses["price"] / 1000 # thousands: no scientific notationprint(price_k.quantile([0.25, 0.5, 0.75, 0.99])) # quartiles and the tailprint(f"skew {price_k.skew():.2f}, log skew {np.log10(price_k).skew():.2f}")0.25 278.5000.50 376.0000.75 560.3750.99 1765.690Name: price, dtype: float64skew 2.67, log skew 0.70skew() |
Shape | Report as typical |
|---|---|---|
| −0.5 … 0.5 | roughly symmetric | mean (or median) |
| 0.5 … 1 | moderately skewed | median |
| above 1 | strongly right-skewed | median; look on a log scale |
| below −1 | strongly left-skewed | median |
- Center: mean, median. Spread: std, IQR = Q3 − Q1, quantiles. Shape: skew, peaks, tails.
- Mean far above median → long right tail (prices, revenue, waiting times).
- A pile-up at the minimum or maximum is often a cap or a floor.
Univariate: categorical
Section titled “Univariate: categorical”customers = pd.read_csv("data/customers.csv")print(customers["contract"].value_counts(normalize=True).round(3))print(customers.select_dtypes("str").nunique())contractmonth-to-month 0.557one-year 0.245two-year 0.198Name: proportion, dtype: float64customer_id 5000signup_date 1542region 4plan 3contract 3payment_method 4dtype: int64- Keys and dates have thousands of levels. They are not categories for analysis.
- A 0/1 column: its mean is the share of 1s.
- The share of the larger target class is the “always predict it” baseline accuracy.
Bivariate: numeric × numeric
Section titled “Bivariate: numeric × numeric”| Pearson | Spearman | |
|---|---|---|
| Measures | straight-line association | monotonic association |
| Computed on | values | ranks |
| One extreme point | can move it a lot | small effect |
| Skewed data, ordinal scores | weak choice | good choice |
| U-shape | misses it | misses it |
| pandas | s.corr(t) |
s.corr(t, method="spearman") |
x = pd.Series(range(1, 21))print(f"{x.corr(x**3):.3f} {x.corr(x**3, method='spearman'):.3f}") # curve: rho = 10.922 1.000Bivariate: number × category and target rates
Section titled “Bivariate: number × category and target rates”base = customers["churned"].mean()table = customers.groupby("contract")["churned"].agg(rate="mean", size="size")table["lift"] = table["rate"] / base # 1.5 = 1.5x the average rateprint(table.round(3)) rate size liftcontractmonth-to-month 0.296 2784 1.535one-year 0.088 1225 0.458two-year 0.032 991 0.168- Always show
sizenext to a rate. - Bin a numeric feature with
pd.cut(s, bins=[...])and passobserved=Truetogroupby. - Merge rare levels (
clip(upper=5), or an “other” level) before you report.
Bivariate: category × category
Section titled “Bivariate: category × category”normalize= |
Adds up to 1 per | Question (rows contract, columns churned) |
|---|---|---|
"index" |
row | churn rate of each contract |
"columns" |
column | contract mix of churners and of stayers |
"all" |
whole table | share of all customers in each cell |
False (default) |
— | raw counts |
mix = pd.crosstab( customers["contract"], customers["churned"], normalize="index", margins=True)print(mix.round(3)) # "All" row = base ratechurned 0 1contractmonth-to-month 0.704 0.296one-year 0.912 0.088two-year 0.968 0.032All 0.807 0.193Multivariate
Section titled “Multivariate”pivot = customers.pivot_table( index="contract", columns="payment_method", values="churned", aggfunc="mean")cells = pivot.stack() # one row per (contract, method)print(cells.idxmax(), f"{cells.max():.3f}")('month-to-month', 'electronic_check') 0.370import matplotlib.pyplot as pltimport seaborn as sns
cols = ["price", "sqft", "school_rating", "distance_to_center_km"]corr = houses[cols].corr(method="spearman")sns.heatmap(corr, annot=True, fmt=".2f", cmap="vlag", vmin=-1, vmax=1) # 0 = whiteplt.show()sns.pairplot(houses.sample(300, random_state=42)[cols], height=2.0) # small sampleplt.show()- Heatmap: a diverging color map with
vmin=-1, vmax=1. - Pairplot: at most 4–5 columns and a few hundred rows.
- Two-key pivot: look for interactions (the effect of A changes with B).
Correlation traps
Section titled “Correlation traps”| Trap | Signal | Check |
|---|---|---|
| Outlier | Pearson and Spearman differ a lot | plot; recompute without the point |
| Non-linearity | small , strong binned pattern | pd.cut + group means |
| Threshold | flat everywhere except one end | compare the first bin with the rest |
| Simpson’s paradox | pooled sign ≠ sign inside groups | repeat inside each level of the confounder |
| Confounding | groups differ in other ways too | compare like with like (same area, per unit) |
| Small group | rate of 0% or 100% | show size; merge rare levels |
| Causation | “X goes with Y, so X causes Y” | name confounders and reverse causation; test with an experiment |
with_lot = houses.dropna(subset=["lot_sqft"])overall = with_lot["lot_sqft"].corr(with_lot["price"], method="spearman")within = with_lot.groupby("neighborhood")[["lot_sqft", "price"]].apply( lambda g: g["lot_sqft"].corr(g["price"], method="spearman"))print(f"overall {overall:+.3f}; positive in {(within > 0).sum()} of {len(within)}")overall -0.148; positive in 8 of 8EDA checklist
Section titled “EDA checklist”| # | Check | Code |
|---|---|---|
| 1 | shape and types | df.shape, df.dtypes.value_counts() |
| 2 | missing values, and why | df.isna().sum(), then inspect the rows |
| 3 | duplicates and keys | df.duplicated().sum(), df["id"].is_unique |
| 4 | ranges, caps, impossible values | df.describe().T[["min", "50%", "max"]] |
| 5 | categories | nunique(), value_counts(dropna=False) |
| 6 | target balance | df[target].value_counts(normalize=True) |
| 7 | leakage suspects | columns made from the target or after the outcome; near-perfect correlation |
missing = customers.isna().sum()print(missing[missing > 0].to_dict(), customers.duplicated().sum(), customers["customer_id"].is_unique){'total_charges': 10} 0 TrueWriting findings
Section titled “Writing findings”<n>. <Claim: what is true, in plain words, with a direction> Evidence: <numbers, group sizes, method and data window> Caveat: <confounder, small group, data quality, time window, causation>| Weak | Strong |
|---|---|
| “Tenure is important.” | “Churners have short tenure: median 6 months against 20.” |
| “Pools add 78%.” | “Pool houses sell for more, but within a neighborhood the gap per sqft is about 5–12%.” |
| “Age does not matter (r ≈ 0).” | “Churn is highest for the youngest and the oldest; r hides the U-shape.” |
Compute every number in code and format it with f-strings. Never type it in.
Gotchas
Section titled “Gotchas”df.corr()on a table with text columns raisesValueErrorin pandas 3. Passnumeric_only=Trueor select the columns.value_counts()drops NaN unlessdropna=False.stack()keeps NaN cells in pandas 3. After masking a matrix, add.dropna().sort_values()on signed correlations puts strong negatives last. Usekey=abs.groupbyon apd.cutresult skips empty bins in pandas 3 (observed=Trueis the default). Passobserved=Trueanyway: pandas 2 defaults toFalseand shows the empty bins.crosstab(normalize="columns")answers “of the churners, which group?”, not “which group churns most?”.- The mean of a skewed column is not “typical”. Report the median and a quantile range.
- A near-zero Pearson value does not mean “no relationship”. Bin and look.
- A rate from a group of 1 is noise. Show the size.
- pandas shows large floats in scientific notation (
1.766e+06). Divide by 1,000 or format with an f-string. - EDA for a model: split off the test set first and explore the training part only.
- Correlation never proves causation. Write the confounders into the caveat.