Skip to content

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.

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
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
import numpy as np
import 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 notation
print(price_k.quantile([0.25, 0.5, 0.75, 0.99])) # quartiles and the tail
print(f"skew {price_k.skew():.2f}, log skew {np.log10(price_k).skew():.2f}")
Output
0.25 278.500
0.50 376.000
0.75 560.375
0.99 1765.690
Name: price, dtype: float64
skew 2.67, log skew 0.70
skew() 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.
customers = pd.read_csv("data/customers.csv")
print(customers["contract"].value_counts(normalize=True).round(3))
print(customers.select_dtypes("str").nunique())
Output
contract
month-to-month 0.557
one-year 0.245
two-year 0.198
Name: proportion, dtype: float64
customer_id 5000
signup_date 1542
region 4
plan 3
contract 3
payment_method 4
dtype: 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.
Pearson rr Spearman ρ\rho
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 = 1
Output
0.922 1.000

Bivariate: 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 rate
print(table.round(3))
Output
rate size lift
contract
month-to-month 0.296 2784 1.535
one-year 0.088 1225 0.458
two-year 0.032 991 0.168
  • Always show size next to a rate.
  • Bin a numeric feature with pd.cut(s, bins=[...]) and pass observed=True to groupby.
  • Merge rare levels (clip(upper=5), or an “other” level) before you report.
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 rate
Output
churned 0 1
contract
month-to-month 0.704 0.296
one-year 0.912 0.088
two-year 0.968 0.032
All 0.807 0.193
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}")
Output
('month-to-month', 'electronic_check') 0.370
plots.py
import matplotlib.pyplot as plt
import 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 = white
plt.show()
sns.pairplot(houses.sample(300, random_state=42)[cols], height=2.0) # small sample
plt.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).
Trap Signal Check
Outlier Pearson and Spearman differ a lot plot; recompute without the point
Non-linearity small rr, 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)}")
Output
overall -0.148; positive in 8 of 8
# 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)
Output
{'total_charges': 10} 0 True
Template
<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.

  • df.corr() on a table with text columns raises ValueError in pandas 3. Pass numeric_only=True or select the columns.
  • value_counts() drops NaN unless dropna=False.
  • stack() keeps NaN cells in pandas 3. After masking a matrix, add .dropna().
  • sort_values() on signed correlations puts strong negatives last. Use key=abs.
  • groupby on a pd.cut result skips empty bins in pandas 3 (observed=True is the default). Pass observed=True anyway: pandas 2 defaults to False and 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.