27. Exploratory data analysis
You have clean tables after module 26. Before you build a chart for a manager or train a model, you need to know what the data says. This module teaches a repeatable way to find out. You describe one column at a time, then pairs of columns, then many columns together. You learn where correlation misleads you. You end with a checklist and a short written report that other people can trust.
The examples use three course datasets: data/customers.csv (which customers churn), data/houses.csv (which features go with higher house prices) and data/sales.csv (where the revenue comes from).
What you will learn
Section titled “What you will learn”- Describe the distribution of a numeric column with
describe(), quantiles and skewness, and the distribution of a categorical column withvalue_counts(normalize=True). - Compare two variables with the right tool for their types: Pearson and Spearman correlation, grouped statistics, and normalized
crosstabtables. - Look at many variables at once with a correlation matrix, a two-category pivot table and a pairplot.
- Recognize the correlation traps: outliers, non-linear relationships, Simpson’s paradox and confounding.
- Run an EDA checklist: data types, missing values, duplicates, ranges, target balance and leakage suspects.
- Write findings as claim → evidence → caveat.
Prerequisites
Section titled “Prerequisites”- 24. pandas fundamentals:
read_csv,loc, boolean filters, new columns,value_counts(),describe(). - 25. pandas advanced:
groupbywithagg,pivot_table,crosstab-style reshaping,unstack(). - 26. Data cleaning: missing values, duplicates, the IQR and z-score outlier rules.
- 09. Standard library power tools: mean, median, quartiles and percentiles.
You need no statistics beyond these. Module 29 adds hypothesis tests. Module 28 teaches plotting in depth. This module draws only the four plots that EDA cannot do without.
Concepts
Section titled “Concepts”What EDA is and why you do it first
Section titled “What EDA is and why you do it first”Exploratory data analysis (EDA) is the first, open-ended look at a dataset. You summarize and plot the data to learn its shape, its quality and its main patterns. You do it before you test a hypothesis or train a model.
EDA answers questions such as:
- Which values are typical, and which are rare or impossible?
- Is the target (the column you want to predict) balanced, or is one class rare?
- Which columns move together? Which groups differ?
- Which patterns are real, and which come from a few odd rows?
The opposite of EDA is confirmatory analysis: you state a hypothesis in advance and test it with a planned method (module 29). EDA generates hypotheses. Confirmatory analysis checks them. If you test a pattern on the same data where you found it, you will often “confirm” noise.
EDA is a loop, not a straight line. Each finding raises the next question.
flowchart LR
Q["Question"] --> S["Summarize<br/>or plot"]
S --> F["Finding"]
F --> C{"Holds up<br/>under checks?"}
C -- "yes" --> R["Write it down:<br/>claim, evidence, caveat"]
C -- "no" --> Q
R --> Q
The work moves from simple to complex:
| Stage | Variables at a time | Typical tools |
|---|---|---|
| Univariate analysis | one | describe(), quantiles, skew(), value_counts(), histogram, box plot |
| Bivariate analysis | two | scatter plot, corr(), groupby().agg(), crosstab() |
| Multivariate analysis | three or more | correlation matrix, heatmap, pivot_table() with two keys, pairplot |
Variable types decide the tools
Section titled “Variable types decide the tools”The type of a column decides which summary makes sense. The mean of a store id is meaningless. The mode (most frequent value) of a price is rarely useful.
| Type | Meaning | Examples in the course data | Univariate summary |
|---|---|---|---|
| Continuous numeric | any value in a range | price, monthly_charges, revenue |
quantiles, mean, median, std, skew, histogram |
| Discrete numeric | counts | support_tickets, bedrooms, quantity |
the same, plus value_counts() when few values exist |
| Ordinal | ordered categories | condition (1–5), school_rating |
value_counts().sort_index(), median |
| Nominal | unordered categories | region, plan, neighborhood |
value_counts(normalize=True), number of levels |
| Binary | two values | churned, has_pool, has_autopay |
the share of 1s |
| Identifier | one value per row | customer_id, house_id |
check uniqueness only |
A 0/1 column is numeric to pandas, but it is a category to you. Its mean is the share of 1s: the mean of churned is the churn rate.
Univariate analysis: numeric columns
Section titled “Univariate analysis: numeric columns”A distribution says which values a column takes and how often. Describe it with three properties:
- Center: a typical value. The mean is the average. The median is the middle value.
- Spread: how far the values scatter. Use the standard deviation and the quantiles: the interquartile range (IQR, module 26) is Q3 − Q1, the width of the middle half of the data.
- Shape: symmetric or skewed, one peak or several, short or long tails.
A quantile is the value below which a given share of the data falls. The 0.9 quantile of price is the price that 90% of houses are below. Series.quantile([0.1, 0.5, 0.9]) returns several at once. describe() shows the 25%, 50% and 75% quantiles by default. Pass percentiles=[...] for others.
Skewness measures how lopsided a distribution is. In a right-skewed (positively skewed) distribution, most values are small and a long tail of large values stretches to the right. Prices, incomes, order sizes and waiting times are usually right-skewed. A left-skewed distribution has its long tail on the left, like the year a house was built (most houses are recent, a few are very old).
The sample skewness is the average cubed distance from the mean, in units of the standard deviation:
Cubing keeps the sign, so large values above the mean push up and large values below push it down. Series.skew() multiplies by a small-sample correction, . For thousands of rows the correction changes almost nothing.
skew() |
Reading | What you usually see |
|---|---|---|
| about −0.5 to 0.5 | roughly symmetric | mean ≈ median |
| 0.5 to 1 (or −1 to −0.5) | moderately skewed | mean pulled toward the tail |
| above 1 (or below −1) | strongly skewed | mean far from median; a few extreme values |
These cut-offs are conventions, not laws. Always look at the histogram too.
Two practical rules follow from skew:
- Report the median, not the mean, as the typical value of a skewed column. The mean follows the tail.
- Look at a skewed column on a log scale. A log transform replaces each value by . It turns ratios into equal steps: 100k → 1M and 1M → 10M are the same distance. A right-skewed price often becomes almost symmetric.
A histogram draws the distribution: it splits the value range into bins (equal intervals) and draws one bar per bin, as high as the number of values in it. A box plot draws the quartiles: a box from Q1 to Q3, a line at the median, whiskers to the furthest values within 1.5 × IQR of the box, and single points beyond the whiskers. A box plot is compact, so it is best to compare several groups side by side.
Univariate analysis: categorical columns
Section titled “Univariate analysis: categorical columns”For a category, count each level. value_counts() gives counts. value_counts(normalize=True) gives shares that add up to 1.
Three things to check:
- Cardinality (module 24): the number of distinct levels (
nunique()). A column with 3 levels is easy to group by. A column with 3,000 levels (a customer id, a free-text field) is not a category for analysis. - Rare levels: a level with 12 rows gives an unstable rate. Note it, or merge it into “other”.
- Missing values:
value_counts()drops NaN by default. Passdropna=Falseto see them.
When the column is the target of a classification, its shares are the class balance. The share of the larger class is your first baseline: a model that always predicts “stays” is right for every customer who stays. If about 81% of customers stay, an accuracy of 81% is worth nothing.
Bivariate analysis: two numeric columns
Section titled “Bivariate analysis: two numeric columns”A scatter plot shows one point per row, with one variable on each axis. It is the first tool for two numeric columns. A number that summarizes the plot is a correlation coefficient: a value from −1 to +1 that says how strongly two variables move together.
The Pearson correlation measures how close the points lie to a straight line:
The numerator is positive when large comes with large . The denominator scales the result into −1 … +1. is a perfect rising line, a perfect falling line, no linear pattern.
The Spearman rank correlation (rho) first replaces each value by its rank (1 for the smallest, 2 for the next, and so on). Then it computes Pearson on the ranks. So it measures how monotonic the relationship is: does keep rising (or keep falling) as rises, in a straight line or not?
A cubic curve shows the difference. rises all the time, but not in a straight line:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport seaborn as sns
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
x = pd.Series(np.arange(1, 21))y = x**3print(f"Pearson: {x.corr(y):.3f}")print(f"Spearman: {x.corr(y, method='spearman'):.3f}")Pearson: 0.922Spearman: 1.000The ranks of x and y are identical, so Spearman is exactly 1. Pearson is lower, because the points bend away from any straight line.
| Pearson | Spearman | |
|---|---|---|
| Measures | linear association | monotonic association |
| Uses | the raw values | the ranks |
| Outliers | one extreme point can move it a lot | less sensitive: an extreme value is just the top rank |
| Skewed data | dominated by the tail | unaffected by a log transform |
| Use when | the relationship looks like a line, no extreme points | skewed data, ordinal scores, outliers, curved but monotonic |
| pandas | s.corr(t) |
s.corr(t, method="spearman") |
Neither coefficient sees a U-shape. If falls and then rises again, both can be close to 0 while the relationship is strong. Always plot, or bin and compare group means.
Bivariate analysis: numeric and categorical
Section titled “Bivariate analysis: numeric and categorical”To compare a numeric column across groups, split by the category and summarize each group: df.groupby("group")["value"].agg(["count", "median", "mean"]). Always include the count. A group with 15 rows can show any median by chance.
For a binary target such as churned, the trick works the other way round too. Group by any category and take the mean of the target: the result is the churn rate per group. Compare each rate with the overall rate, the base rate. The ratio of a group rate to the base rate is the lift: a lift of 1.5 means the group churns 1.5 times as often as the average customer.
A box plot per group shows the same comparison as a picture, with the spread and the outliers.
Bivariate analysis: two categorical columns
Section titled “Bivariate analysis: two categorical columns”Module 25 built contingency tables with pd.crosstab(df["a"], df["b"]): a count of the rows for each pair of levels. In EDA, the normalize argument matters most. It turns counts into shares, and the choice decides which question the table answers:
normalize= |
Each … adds up to 1 | Question it answers (rows = contract, columns = churned) |
|---|---|---|
"index" |
row | Of the month-to-month customers, what share churned? |
"columns" |
column | Of the churned customers, what share were month-to-month? |
"all" |
whole table | What share of all customers are month-to-month churners? |
margins=True adds a total row and column (the margins). With normalize="index", the total row is the overall rate, which is the base rate to compare against.
Put the variable that you think explains in the rows and the outcome in the columns, then use normalize="index". That reads as “the outcome rate for each group”.
Multivariate analysis
Section titled “Multivariate analysis”Real effects rarely live in one pair of columns. Three tools look at many at once:
- A correlation matrix holds the correlation of every pair of numeric columns.
df.corr(numeric_only=True)builds it. A heatmap colors each cell by its value, so strong pairs stand out. - A pivot table with two category keys shows a value for every combination, for example the churn rate for each
contract×payment_methodpair. It reveals interactions: the effect of one variable depends on the level of another. - A pairplot draws a grid of scatter plots for every pair of a few columns, with histograms on the diagonal. Use it on a sample of a few hundred rows and at most 4–5 columns, or it becomes slow and unreadable.
A correlation matrix also finds redundant features: two inputs that carry almost the same information (house size and number of bathrooms). Redundancy matters for linear models (module 35) and for interpretation (module 43).
Correlation pitfalls
Section titled “Correlation pitfalls”A correlation is one number for a whole cloud of points. It can mislead in five ways:
| Trap | What happens | Defense |
|---|---|---|
| Outliers | One extreme point moves Pearson by a lot, up or down. | Plot. Compare with Spearman. Recompute without the point. |
| Non-linearity | A U-shape, a curve or a threshold effect (flat everywhere, then a sharp change past one cut-off) gives a small for a strong relationship. | Plot, or bin x and compare group means. |
| Simpson’s paradox | A trend in the pooled data reverses (or vanishes) inside the subgroups. | Repeat the analysis inside each group of a likely confounder. |
| Confounding | A third variable is linked to both columns, so they correlate more (or less) than any direct link explains. | Ask what else differs between the groups. Compare like with like. |
| Small groups | A rate based on 5 rows looks extreme by chance. | Always show the count next to a rate. |
A confounder is a variable that influences both the “cause” and the “effect” that you look at. Houses with a pool sell for more. Pools are also more common in expensive neighborhoods and on large houses. The neighborhood and the size drive both the pool and the price, so the raw price gap exaggerates what a pool is worth.
flowchart TB
N["Neighborhood and size<br/>(confounder)"] --> P["has_pool"]
N --> Y["price"]
P -. "small direct effect" .-> Y
Simpson’s paradox is the extreme case: the confounder reverses the sign. You will see one in the course data in Example 7.
Correlation is not causation. A correlation says that two columns move together in this data. It does not say that changing one changes the other. Three other explanations always compete: a confounder, reverse causation (the outcome drives the “cause”: customers who already plan to leave open more support tickets) and chance. EDA finds candidates. An experiment (module 29, A/B tests) or domain knowledge is needed to claim a cause.
The EDA checklist
Section titled “The EDA checklist”Run the same checks on every new table, in this order. Each one can stop you before you analyze garbage.
| # | Check | pandas | Look for |
|---|---|---|---|
| 1 | Shape and data types | df.shape, df.dtypes |
numbers stored as text, dates stored as text, ids read as numbers |
| 2 | Missing values | df.isna().sum(), df.isna().mean() |
which columns, how many, and why (random or structural) |
| 3 | Duplicates and keys | df.duplicated().sum(), df["id"].is_unique |
repeated rows, a key that is not unique; the unit of analysis (what one row is: a line, an order, a customer, a day) |
| 4 | Ranges | df.describe(), min(), max() |
impossible values (negative ages), caps and floors (a pile-up at 72) |
| 5 | Categories | nunique(), value_counts(dropna=False) |
spelling variants, rare levels, unexpected levels |
| 6 | Target balance | df["target"].value_counts(normalize=True) |
a rare class; the baseline score |
| 7 | Leakage suspects | correlation with the target, plus when each column is recorded | a column that is known only after the outcome, or computed from it |
Data leakage (module 33 covers it in depth) means that a model sees information during training that it will not have when it makes real predictions. A leakage suspect is a column that may carry such information. Warning signs:
- The column is recorded after the outcome: a “cancellation reason” in a churn table, the final sale price in a listing table.
- The column is computed from the target:
revenuewhen you predictquantity,price_per_sqftwhen you predictprice. - The column correlates with the target almost perfectly. Real predictors rarely do.
You cannot prove leakage from the data alone. List the suspects and ask the data owner when and how each column is filled.
Writing findings: claim → evidence → caveat
Section titled “Writing findings: claim → evidence → caveat”A finding is one sentence that someone can act on, backed by numbers. Write each finding in three parts:
- Claim: what is true, in plain words. “Month-to-month customers churn far more often.”
- Evidence: the numbers and how you got them. “29.6% churned against 3.2% on two-year contracts (
crosstab, 5,000 customers).” - Caveat: what the evidence does not show. “Observational data: contract choice may reflect intent to leave, so a forced switch may not cut churn.”
The caveat is a limit on the claim: a confounder, a small group, a data-quality problem or a time window. It is not a weakness of your report. It tells the reader how far to trust the claim and what to check next.
| Weak finding | Why it is weak | Strong version |
|---|---|---|
| “Tenure is important.” | no direction, no size | “Churners have short tenure: median 6 months, against 20 for customers who stay.” |
| “Pools add 78% to the price.” | confounded | “Pool houses sell for more, but they are larger and in pricier areas; within a neighborhood, the gap per square foot is about 5–12%.” |
| “Age does not matter (r = −0.039).” | misses a U-shape | “Churn is highest for the youngest and oldest customers; a linear correlation hides this.” |
Worked examples
Section titled “Worked examples”Example 1 — Run the EDA checklist on the churn table
Section titled “Example 1 — Run the EDA checklist on the churn table”Goal: Before a retention team asks “why do customers leave?”, check that data/customers.csv is fit to answer it.
Step 1 — Check the shape and the data types
Section titled “Step 1 — Check the shape and the data types”customers = pd.read_csv("data/customers.csv")print(customers.shape)print(customers.dtypes.value_counts())print(customers.select_dtypes("str").columns.tolist())(5000, 15)str 6int64 6float64 3Name: count, dtype: int64['customer_id', 'signup_date', 'region', 'plan', 'contract', 'payment_method']The table has 5,000 rows and 15 columns. pandas 3 reads text as the str dtype. signup_date is text, so date arithmetic needs pd.to_datetime() first. The id is text too, which is right: nobody adds customer ids.
Step 2 — Count the missing values and ask why
Section titled “Step 2 — Count the missing values and ask why”missing = customers.isna().sum()print(missing[missing > 0])new_customers = customers.loc[customers["total_charges"].isna(), "tenure_months"]print(new_customers.value_counts())total_charges 10dtype: int64tenure_months0 10Name: count, dtype: int64Only total_charges has gaps, 10 of them. All 10 rows have tenure_months 0. These are brand-new customers who have not been billed yet. The gap is structural: it has a reason, and the right fill value is 0, not the median.
Step 3 — Check duplicates and the key
Section titled “Step 3 — Check duplicates and the key”print("duplicate rows:", customers.duplicated().sum())print("customer_id unique:", customers["customer_id"].is_unique)duplicate rows: 0customer_id unique: TrueNo row repeats and every customer appears once. One row is one customer, so a mean over rows is a mean over customers.
Step 4 — Check the ranges
Section titled “Step 4 — Check the ranges”numeric = customers.select_dtypes("number")print(numeric.describe().T[["min", "50%", "max"]])print(customers["tenure_months"].value_counts().sort_index().tail(5)) min 50% maxage 18.00 42.000 80.00has_autopay 0.00 1.000 1.00tenure_months 0.00 17.000 72.00monthly_charges 28.05 58.865 143.24total_charges 29.55 961.190 8322.61support_tickets 0.00 1.000 9.00logins_last_30d 0.00 10.000 60.00avg_session_minutes 1.00 12.900 68.10churned 0.00 0.000 1.00tenure_months68 969 1070 1671 1172 220Name: count, dtype: int64Every range is plausible: ages 18–80, at most 9 tickets, no negative charges. Tenures 68 to 71 have 9 to 16 customers each, but 72 has 220. A pile-up at the maximum is a cap: the oldest customers are all recorded as 72, whatever their real tenure. Treat 72 as “72 or more”.
Step 5 — Check the target balance
Section titled “Step 5 — Check the target balance”balance = customers["churned"].value_counts(normalize=True)print(balance)print(f"Always predicting 'stays' is right {balance[0]:.1%} of the time.")churned0 0.8071 0.193Name: proportion, dtype: float64Always predicting 'stays' is right 80.7% of the time.19.3% of customers churned. The classes are imbalanced, about 1 to 4. Any model must beat the 80.7% accuracy of the “nobody churns” guess, and accuracy is a poor score here (module 36).
Step 6 — List the redundancy and leakage suspects
Section titled “Step 6 — List the redundancy and leakage suspects”billed = customers["monthly_charges"] * customers["tenure_months"]ratio = customers["total_charges"] / billedprint(ratio.describe()[["min", "50%", "max"]].round(3))print("rows sorted by id:", customers["customer_id"].is_monotonic_increasing)print("signup date never decreases:", customers["signup_date"].is_monotonic_increasing)min 0.94050% 0.985max 1.030dtype: float64rows sorted by id: Truesignup date never decreases: TrueThe two findings are different kinds of suspects:
total_chargesis a redundancy suspect. It is almost exactlymonthly_charges × tenure_months(ratio 0.94 to 1.03). It adds little new information, and a linear model would split one effect between two columns. Ask the data owner when it is computed, in case it is updated after a customer leaves.customer_idis an id that encodes time. The rows are sorted by id, andsignup_datenever decreases along them, so a higher id means a later signup and a shorter tenure. A model could learn tenure from the id, which breaks as soon as new ids are issued. Drop it from any model.
Common mistakes:
- Filling
total_chargeswith the median. The 10 gaps are new customers, so the median (961) invents a bill. - Reading 72 months as “exactly six years”. It is a cap.
- Skipping the target balance and celebrating 80% accuracy.
Example 2 — Describe the distribution of house prices
Section titled “Example 2 — Describe the distribution of house prices”Goal: A pricing analyst asks “what does a typical house cost, and how wide is the range?” Answer it for data/houses.csv.
Step 1 — Summarize the price with extra quantiles
Section titled “Step 1 — Summarize the price with extra quantiles”houses = pd.read_csv("data/houses.csv")price_k = houses["price"] / 1000print(price_k.describe(percentiles=[0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99]).round(1))count 3000.0mean 476.5std 318.8min 117.51% 167.010% 223.425% 278.550% 376.075% 560.490% 848.299% 1765.7max 3730.5Name: price, dtype: float64Dividing by 1,000 keeps the output readable (prices in thousands). The median house sells for 376k, but the mean is 476.5k. The 99% quantile is about 1.77 million and the maximum is 3.73 million. The middle half of the houses (Q1 to Q3) lies between 278.5k and 560.4k.
Step 2 — Measure the skew on the raw and the log scale
Section titled “Step 2 — Measure the skew on the raw and the log scale”log_price = np.log10(houses["price"])print(f"skew of price: {houses['price'].skew():.3f}")print(f"skew of log10 price: {log_price.skew():.3f}")print(f"mean / median: {houses['price'].mean() / houses['price'].median():.3f}")skew of price: 2.666skew of log10 price: 0.699mean / median: 1.267A skew of 2.67 is strong right skew: the mean is 27% above the median. On the log scale the skew drops to 0.70, a moderate value. The log removes most of the skew, and the rest comes from the expensive neighborhoods in the tail. That is why many price models predict the log price (module 35).
Step 3 — Plot the histogram on both scales
Section titled “Step 3 — Plot the histogram on both scales”fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))sns.histplot(x=price_k, bins=60, ax=axes[0])axes[0].axvline(price_k.median(), color="black", linestyle="--", label="median")axes[0].axvline(price_k.mean(), color="tab:red", label="mean")axes[0].set(xlabel="price (thousand USD)", title="Raw scale: long right tail")axes[0].legend()sns.histplot(x=log_price, bins=60, ax=axes[1])axes[1].set(xlabel="log10(price)", title="Log scale: much less skewed")fig.tight_layout()plt.show()
The raw histogram is a tall hump on the left and a long thin tail on the right. The mean (red) sits right of the median (dashed), pulled by the tail. On the log scale the same data forms one hump with a much shorter right tail.
Step 4 — Read the tail with quantiles
Section titled “Step 4 — Read the tail with quantiles”top_cut = houses["price"].quantile(0.99)top = houses[houses["price"] >= top_cut]print(f"99% quantile: {top_cut:,.0f}")print(f"houses above 1M: {(houses['price'] > 1_000_000).mean():.1%}")print(top["neighborhood"].value_counts())99% quantile: 1,765,690houses above 1M: 6.3%neighborhoodLakeview 19Oak Hill 10Maple Grove 1Name: count, dtype: int646.3% of the houses sold for more than 1 million. Of the top 1% (30 houses), 29 sit in Lakeview and Oak Hill. The tail is not random noise: it is a small group of expensive neighborhoods. The data dictionary confirms that large houses there are genuine, so you keep them. The one Maple Grove house is H0542, and Example 5 shows that it is a data error.
Common mistakes:
- Reporting the mean (476.5k) as the “typical” price of a skewed column. Use the median.
- Deleting the tail as “outliers” without checking what it is. Here it is a real market segment.
- Too few bins. With 10 bins the long tail disappears into one bar; use 40–60 for a few thousand rows.
Example 3 — Profile the categorical columns of the sales table
Section titled “Example 3 — Profile the categorical columns of the sales table”Goal: A category manager asks “where do our sales lines and our revenue come from?” Profile the categories of data/sales.csv, alone and two at a time.
Step 1 — Count the levels of each text column
Section titled “Step 1 — Count the levels of each text column”sales = pd.read_csv("data/sales.csv")print(sales.select_dtypes("str").nunique())order_id 14877order_date 731customer_id 3254store_id 12region 4channel 2product_id 30product 30category 6dtype: int64order_id, order_date and customer_id have thousands of levels: they are keys and dates, not categories. region, channel, category and store_id have few levels, so you can group by them.
Step 2 — Get shares with value_counts(normalize=True)
Section titled “Step 2 — Get shares with value_counts(normalize=True)”print(sales["channel"].value_counts(normalize=True).round(3))print(sales["discount"].value_counts(normalize=True).sort_index().round(3))channelstore 0.58online 0.42Name: proportion, dtype: float64discount0.00 0.6750.05 0.1310.10 0.1230.20 0.071Name: proportion, dtype: float6458% of lines are sold in a store and 42% online. Two of three lines have no discount. discount is numeric, but it has only four values, so it behaves like an ordinal category.
Step 3 — Compare the share of lines with the share of revenue
Section titled “Step 3 — Compare the share of lines with the share of revenue”by_category = sales.groupby("category")["revenue"].agg(lines="size", revenue="sum")shares = (by_category / by_category.sum()).round(3)print(shares.sort_values("revenue", ascending=False)) lines revenuecategoryElectronics 0.195 0.503Home 0.161 0.187Sports 0.165 0.151Clothing 0.198 0.087Beauty 0.154 0.042Books 0.127 0.030Electronics is 19.5% of the lines but 50.3% of the revenue. Books is 12.7% of the lines and only 3.0% of the revenue. A count chart and a revenue chart tell different stories. Say which one you show.
Step 4 — Pivot the revenue by two categories
Section titled “Step 4 — Pivot the revenue by two categories”pivot = sales.pivot_table( index="category", columns="channel", values="revenue", aggfunc="sum") / 1000pivot["online_share"] = pivot["online"] / (pivot["online"] + pivot["store"])print(pivot.sort_values("online_share").round(3))channel online store online_sharecategorySports 226.772 317.337 0.417Books 44.645 62.263 0.418Home 284.066 388.229 0.423Clothing 133.153 181.533 0.423Beauty 63.758 86.659 0.424Electronics 767.072 1041.036 0.424The pivot table shows the revenue (in thousands) for each category × channel cell. Dividing by 1,000 keeps pandas from switching to scientific notation. The online share is between 41.7% and 42.4% in every category. The channel mix does not depend much on the category.
Step 5 — Normalize a crosstab to compare the years
Section titled “Step 5 — Normalize a crosstab to compare the years”sales["year"] = sales["order_date"].str[:4]mix = pd.crosstab(sales["year"], sales["channel"], normalize="index", margins=True)print(mix.round(3))channel online storeyear2023 0.368 0.6322024 0.462 0.538All 0.420 0.580With normalize="index", each row adds up to 1, so each row is the channel mix of one year. The online share grew from 36.8% to 46.2%. The All row is the overall mix of both years. This is the real change in the sales table: the channel shifts over time, not across categories.
Common mistakes:
- Using
nunique()on keys and reading them as categories. - Showing line counts to answer a revenue question.
- Normalizing by
"columns"when you want a mix per row. Check which direction adds up to 1.
Example 4 — Find the features linked to churn, one at a time
Section titled “Example 4 — Find the features linked to churn, one at a time”Goal: List which customer features go with churn, and how strongly, as input for the retention team.
Step 1 — Compare numeric features across the two target groups
Section titled “Step 1 — Compare numeric features across the two target groups”features = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]print(customers.groupby("churned")[features].agg(["median", "mean"]).T.round(2))churned 0 1tenure_months median 20.00 6.00 mean 25.79 11.72monthly_charges median 58.27 61.79 mean 59.47 66.58support_tickets median 1.00 1.00 mean 1.12 1.74logins_last_30d median 10.00 9.00 mean 12.11 10.20.T transposes the result, so each row is one feature and one statistic. The median churner has a tenure of 6 months, against 20 for customers who stay. Churners also pay more (mean 66.58 against 59.47) and log in less. The median number of tickets is 1 in both groups, but the means differ (1.74 against 1.12). A count with few distinct values has a coarse median; compare means or rates for it (Step 5).
Step 2 — Draw a box plot of tenure per group
Section titled “Step 2 — Draw a box plot of tenure per group”stayed = customers.loc[customers["churned"] == 0, "tenure_months"]left = customers.loc[customers["churned"] == 1, "tenure_months"]fig, ax = plt.subplots(figsize=(6, 4))ax.boxplot([stayed, left], tick_labels=["stayed (0)", "churned (1)"])ax.set(ylabel="tenure (months)", title="Churners have much shorter tenure")plt.show()
The boxes overlap only between 10 and 16 months, and the churner median (6) lies below the whole stayed box. Churners cluster in the first year. The single points above the churner whisker are long-tenure customers who still left: they are rare, not impossible.
Step 3 — Cross-tabulate the contract and the churn
Section titled “Step 3 — Cross-tabulate the contract and the churn”churn_by_contract = pd.crosstab( customers["contract"], customers["churned"], normalize="index", margins=True)print(churn_by_contract.round(3))print(customers["contract"].value_counts())churned 0 1contractmonth-to-month 0.704 0.296one-year 0.912 0.088two-year 0.968 0.032All 0.807 0.193contractmonth-to-month 2784one-year 1225two-year 991Name: count, dtype: int64Read the column 1. 29.6% of month-to-month customers churn, against 8.8% on one-year and 3.2% on two-year contracts. The All row is the base rate, 19.3%. Month-to-month customers have a lift of about 1.5 (29.6 / 19.3), and they are the largest group (2,784 customers).
Step 4 — Bin a numeric feature to see its shape
Section titled “Step 4 — Bin a numeric feature to see its shape”age_band = pd.cut(customers["age"], bins=[17, 25, 35, 45, 55, 65, 80])by_age = customers.groupby(age_band, observed=True)["churned"].agg(["mean", "size"])print(by_age.round(3))print(f"Pearson r(age, churned): {customers['age'].corr(customers['churned']):.3f}") mean sizeage(17, 25] 0.307 502(25, 35] 0.221 1044(35, 45] 0.147 1427(45, 55] 0.149 1256(55, 65] 0.195 589(65, 80] 0.363 182Pearson r(age, churned): -0.039pd.cut splits the ages into bands. The churn rate falls from 30.7% (ages 18–25) to about 15% (36–55) and rises again to 36.3% (66–80). That is a U-shape. The Pearson correlation is only −0.039, because the falling half and the rising half cancel out. A correlation table alone would call age useless.
Step 5 — Check the group sizes before you trust a rate
Section titled “Step 5 — Check the group sizes before you trust a rate”by_tickets = customers.groupby("support_tickets")["churned"].agg(["mean", "size"])print(by_tickets.round(3)) mean sizesupport_tickets0 0.132 15371 0.160 17422 0.207 10273 0.326 4574 0.473 1845 0.559 346 0.688 167 0.000 18 1.000 19 1.000 1Churn rises steadily from 13.2% at 0 tickets to 55.9% at 5 tickets. Above 6 tickets each group has 1 customer, so the rates 0.0 and 1.0 are noise. Merge the tail into a “5+” group before you report it.
Common mistakes:
- Reading
normalize="index"output column0instead of1. Name the columns or select[1]. - Trusting a near-zero correlation. Bin the feature and look at the shape.
- Reporting a rate without its count.
Example 5 — Compare Pearson and Spearman on house size and price
Section titled “Example 5 — Compare Pearson and Spearman on house size and price”Goal: Measure how strongly house size goes with price, and see how one bad row changes the answer.
Step 1 — Compute both coefficients for three features
Section titled “Step 1 — Compute both coefficients for three features”for column in ["sqft", "school_rating", "distance_to_center_km"]: pearson = houses[column].corr(houses["price"]) spearman = houses[column].corr(houses["price"], method="spearman") print(f"{column:<22} Pearson {pearson:6.3f} Spearman {spearman:6.3f}")sqft Pearson 0.730 Spearman 0.679school_rating Pearson 0.566 Spearman 0.681distance_to_center_km Pearson -0.143 Spearman -0.325Series.corr skips rows where either value is missing, so the 90 blank school ratings do not break it. Size has the strongest linear association with price. For distance, Spearman (−0.325) is more than twice as strong as Pearson (−0.143). A few very expensive houses sit at middle distances and pull hard on Pearson; ranks limit their pull. The pairplot in Example 6 shows that this relationship is not even a straight trend.
Step 2 — Zoom in on one neighborhood and find the odd point
Section titled “Step 2 — Zoom in on one neighborhood and find the odd point”maple = houses[houses["neighborhood"] == "Maple Grove"].copy()maple["price_per_sqft"] = maple["price"] / maple["sqft"]print(len(maple))top3 = maple.nlargest(3, "price_per_sqft")print(top3[["house_id", "sqft", "price", "price_per_sqft"]])454 house_id sqft price price_per_sqft541 H0542 3770 2660000 705.5701519 H1520 1620 687000 424.074422 H0423 1380 548000 397.101Inside one neighborhood, size should explain price well. Price per square foot is a quick way to find a house that does not fit. H0542 costs 66% more per square foot than the next house (705.57 against 424.07). The data dictionary lists it as an injected outlier, a data-entry error.
Step 3 — Plot the neighborhood with the odd point marked
Section titled “Step 3 — Plot the neighborhood with the odd point marked”odd = maple["house_id"] == "H0542"fig, ax = plt.subplots(figsize=(6, 4))price_k_maple = maple["price"] / 1000ax.scatter(maple.loc[~odd, "sqft"], price_k_maple[~odd], s=10, alpha=0.6)ax.scatter(maple.loc[odd, "sqft"], price_k_maple[odd], color="tab:red", s=40)ax.annotate("H0542", (3770, 2660), xytext=(2600, 2400), arrowprops={"arrowstyle": "->"})ax.set(xlabel="sqft", ylabel="price (thousand USD)", title="Maple Grove: one odd point")plt.show()
The points form a clear rising band. H0542 sits far above it. It also sits far to the right, so it pulls a straight line toward it. That is exactly the kind of point that moves Pearson.
Step 4 — Remove the point and recompute
Section titled “Step 4 — Remove the point and recompute”clean = maple[~odd]for name, frame in [("with H0542", maple), ("without", clean)]: pearson = frame["sqft"].corr(frame["price"]) spearman = frame["sqft"].corr(frame["price"], method="spearman") print(f"{name:<11} n={len(frame)} Pearson {pearson:.3f} Spearman {spearman:.3f}")ranks = maple[["sqft", "price"]].rank(ascending=False)print("H0542 rank (1 = largest):", ranks[odd].iloc[0].to_dict())with H0542 n=454 Pearson 0.734 Spearman 0.766without n=453 Pearson 0.809 Spearman 0.765H0542 rank (1 = largest): {'sqft': 6.0, 'price': 1.0}One row out of 454 moved Pearson from 0.734 to 0.809. Spearman barely changed (0.766 to 0.765). In ranks, H0542 is the 6th largest house and the most expensive one: a small rank error, whatever its price. When one point can change your story, report Spearman, or report both with and without the point.
Common mistakes:
- Deleting a point because it lowers the correlation. Remove a row only when you can show it is wrong (here: the data dictionary and an impossible price per square foot).
- Comparing Pearson values from groups with very different spreads. A neighborhood with a narrow price range has a lower even with the same underlying relationship.
Example 6 — Look at many house features at once
Section titled “Example 6 — Look at many house features at once”Goal: Give the modeling team one picture of how the house features relate to price and to each other.
Step 1 — Build a Spearman correlation matrix
Section titled “Step 1 — Build a Spearman correlation matrix”columns = [ "price", "sqft", "bedrooms", "bathrooms", "school_rating", "distance_to_center_km", "lot_sqft", "condition", "year_built",]corr = houses[columns].corr(method="spearman")print(corr["price"].drop("price").sort_values(ascending=False).round(3))school_rating 0.681sqft 0.679bathrooms 0.582bedrooms 0.575condition 0.249year_built 0.194lot_sqft -0.148distance_to_center_km -0.325Name: price, dtype: float64Spearman fits here, because price is skewed and several features are ordinal scores. School rating and size have the strongest association with price. Distance and lot size have negative correlations. Keep the lot-size sign in mind for Example 7.
Step 2 — Draw the matrix as a heatmap
Section titled “Step 2 — Draw the matrix as a heatmap”fig, ax = plt.subplots(figsize=(8, 6.5))sns.heatmap(corr, annot=True, fmt=".2f", cmap="vlag", vmin=-1, vmax=1, ax=ax)ax.set_title("Spearman correlation, houses.csv")fig.tight_layout()plt.show()
A diverging color map uses two hues that meet at a neutral middle color. Here positive pairs are red and negative pairs blue, with white at 0. Fixing vmin=-1, vmax=1 keeps 0 white whatever the data. The red block of sqft, bedrooms and bathrooms shows three features that measure almost the same thing: house size.
Step 3 — Rank the strongest feature pairs
Section titled “Step 3 — Rank the strongest feature pairs”upper = corr.where(np.triu(np.ones(corr.shape, dtype=bool), k=1))pairs = upper.stack().dropna().rename("rho").to_frame()pairs["abs_rho"] = pairs["rho"].abs()print(pairs.sort_values("abs_rho", ascending=False).head(5).round(3)) rho abs_rhobedrooms bathrooms 0.873 0.873sqft bedrooms 0.814 0.814 bathrooms 0.808 0.808distance_to_center_km lot_sqft 0.794 0.794price school_rating 0.681 0.681np.triu(..., k=1) keeps the upper triangle without the diagonal, so each pair appears once. stack() turns the matrix into one row per cell. In pandas 3 it keeps the masked NaN cells, so dropna() removes them and each pair appears once. The top pairs are size measures (redundant features) and distance with lot size: outer houses have larger plots.
Step 4 — Draw a pairplot on a sample
Section titled “Step 4 — Draw a pairplot on a sample”sample = houses.sample(300, random_state=42)sample = sample.assign(price_k=sample["price"] / 1000)grid = sns.pairplot( sample[["sqft", "school_rating", "distance_to_center_km", "price_k"]], height=2.0, plot_kws={"s": 12, "alpha": 0.6},)plt.show()
A pairplot shows the shapes that the matrix hides. Price against size fans out: the spread grows with size, which is typical for a skewed target. School rating is a set of stripes, because it takes only whole values. Price against distance is a hump, not a line: the most expensive houses sit 7–9 km out, in Lakeview and Oak Hill (see the medians in Example 7). A single correlation of −0.325 hides that shape. A 300-row sample keeps the plot fast and readable.
Common mistakes:
houses.corr()on the whole table. In pandas 3 it raisesValueErroron text columns. Select the columns, or passnumeric_only=True.- Reading the full matrix twice. Each pair appears above and below the diagonal.
- A pairplot of 3,000 rows and 12 columns: 144 panels of overplotted points.
Example 7 — Catch Simpson’s paradox in house prices
Section titled “Example 7 — Catch Simpson’s paradox in house prices”Goal: The matrix says larger lots go with lower prices. Check whether that is true for a buyer who compares houses in the same area.
Step 1 — Measure the overall correlation
Section titled “Step 1 — Measure the overall correlation”with_lot = houses.dropna(subset=["lot_sqft"])overall = with_lot["lot_sqft"].corr(with_lot["price"], method="spearman")print(f"all houses: Spearman {overall:.3f} (n={len(with_lot)})")all houses: Spearman -0.148 (n=2910)Across all houses, a bigger lot goes with a lower price.
Step 2 — Repeat the correlation inside each neighborhood
Section titled “Step 2 — Repeat the correlation inside each neighborhood”within = with_lot.groupby("neighborhood")[["lot_sqft", "price"]].apply( lambda g: g["lot_sqft"].corr(g["price"], method="spearman"))print(within.round(3).sort_values())print("positive in", (within > 0).sum(), "of", len(within), "neighborhoods")neighborhoodCedar Park 0.026Maple Grove 0.039Oak Hill 0.048Westfield 0.048Lakeview 0.049Old Town 0.050Riverside 0.092Downtown 0.110dtype: float64positive in 8 of 8 neighborhoodsInside every one of the 8 neighborhoods, the sign flips: a bigger lot goes with a slightly higher price. The overall trend reverses in every subgroup. This is Simpson’s paradox, in the course data.
Step 3 — Find the confounder
Section titled “Step 3 — Find the confounder”profile_columns = ["lot_sqft", "distance_to_center_km", "price"]profile = with_lot.groupby("neighborhood")[profile_columns].median()print(profile.sort_values("lot_sqft")) lot_sqft distance_to_center_km priceneighborhoodDowntown 2875.0 0.9 340250.0Old Town 3070.0 1.5 334000.0Riverside 4730.0 4.0 476500.0Lakeview 7330.0 7.5 777000.0Oak Hill 7760.0 9.0 727500.0Maple Grove 9280.0 11.0 400500.0Westfield 10730.0 13.5 265500.0Cedar Park 12225.0 15.9 248750.0The two outer areas, Westfield and Cedar Park, have the biggest lots and the lowest prices. The small-lot central areas, Downtown and Old Town, cost more than them. The most expensive areas, Lakeview and Oak Hill, have mid-size lots, so the medians form a hump, not a line. The neighborhood is linked to both the lot size and the price. Pooling all houses lets the cheap big-lot areas pull the overall slope negative, although no single area has a negative slope.
Step 4 — Check a second confounded effect: the pool premium
Section titled “Step 4 — Check a second confounded effect: the pool premium”pool = houses.groupby("has_pool")["price"].median()print(f"raw median price gap: {pool[1] / pool[0] - 1:+.1%}")houses["price_per_sqft"] = houses["price"] / houses["sqft"]per_area = houses.pivot_table( index="neighborhood", columns="has_pool", values="price_per_sqft", aggfunc="median")print((per_area[1] / per_area[0] - 1).round(3).sort_values())pool_count = houses.groupby("neighborhood")["has_pool"].agg(["mean", "sum"])print(pool_count.loc[["Old Town", "Westfield", "Lakeview"]].round(3))raw median price gap: +78.1%neighborhoodWestfield -0.140Maple Grove 0.047Riverside 0.054Downtown 0.067Lakeview 0.070Cedar Park 0.090Oak Hill 0.123Old Town 0.248dtype: float64 mean sumneighborhoodOld Town 0.011 3Westfield 0.040 18Lakeview 0.300 92Pool houses sell for 78% more overall. Compared like with like (same neighborhood, per square foot), the premium is 5–12% in six neighborhoods. Old Town (+24.8%) and Westfield (−14.0%) are the exceptions, and Old Town has only 3 pool houses. The raw gap is mostly the confounders: pool houses are bigger and sit in pricier areas.
Common mistakes:
- Reporting the pooled correlation as “larger lots lower the price”.
- Splitting by a group that has only a few rows per level. Check the counts first, as the Old Town pool shows.
- Thinking that the within-group answer is now “the causal effect”. It is closer, but other confounders (age, condition) may remain.
Example 8 — Write a short findings report
Section titled “Example 8 — Write a short findings report”Goal: Turn the house-price EDA into three findings for a pricing manager, each with claim, evidence and caveat. The code computes every number, so the report stays correct when the data changes.
Step 1 — Compute the evidence
Section titled “Step 1 — Compute the evidence”median_price = houses["price"].median()rho_sqft = corr.loc["sqft", "price"]rho_school = corr.loc["school_rating", "price"]size_trio = ["sqft", "bedrooms", "bathrooms"]upper_3 = np.triu(np.ones((3, 3), dtype=bool), k=1)size_pairs = corr.loc[size_trio, size_trio].where(upper_3).stack().dropna()within_sqft = houses.groupby("neighborhood")[["sqft", "price"]].apply( lambda g: g["sqft"].corr(g["price"], method="spearman"))by_area = houses.groupby("neighborhood")["price"].median().sort_values()area_ratio = by_area.iloc[-1] / by_area.iloc[0]pool_gap = pool[1] / pool[0] - 1gaps = per_area[1] / per_area[0] - 1few_pools = pool_count.index[pool_count["sum"] < 20].tolist()typical_gaps = gaps.drop(few_pools)print(f"{median_price=:,.0f} {rho_sqft=:.3f} {rho_school=:.3f} {area_ratio=:.2f}")print(f"size pairs rho {size_pairs.min():.2f}-{size_pairs.max():.2f}; " f"sqft within areas {within_sqft.min():.2f}-{within_sqft.max():.2f}")print(f"{pool_gap=:.3f}; per sqft {typical_gaps.min():.3f}-{typical_gaps.max():.3f}")print("areas with fewer than 20 pool houses:", few_pools)median_price=376,000 rho_sqft=0.679 rho_school=0.681 area_ratio=3.12size pairs rho 0.81-0.87; sqft within areas 0.53-0.87pool_gap=0.781; per sqft 0.047-0.123areas with fewer than 20 pool houses: ['Downtown', 'Old Town', 'Westfield']The = inside the f-string braces prints the name and the value: a quick way to check the numbers before you write sentences around them. corr is the Spearman matrix of Example 6, and pool_count comes from Example 7. Neighborhoods with fewer than 20 pool houses are left out of the pool range by a rule, not by hand.
Step 2 — Print the report
Section titled “Step 2 — Print the report”findings = [ ( "Size and school rating have the strongest association with price.", f"Spearman {rho_sqft:.2f} (sqft), {rho_school:.2f} (school rating), " f"{len(houses):,} sales; sqft {within_sqft.min():.2f}-" f"{within_sqft.max():.2f} per area.", f"sqft, bedrooms, bathrooms overlap (rho {size_pairs.min():.2f}-" f"{size_pairs.max():.2f}): one signal, not three.", ), ( "The price level differs strongly by neighborhood.", f"Median price ranges from {by_area.iloc[0]:,.0f} ({by_area.index[0]}) " f"to {by_area.iloc[-1]:,.0f} ({by_area.index[-1]}), x{area_ratio:.1f}.", "Neighborhoods differ in size and age mix too; compare per sqft.", ), ( "The pool premium is far smaller than the raw gap suggests.", f"Raw median gap {pool_gap:+.0%}; per sqft within a neighborhood " f"{typical_gaps.min():+.0%} to {typical_gaps.max():+.0%}.", f"Observational; under 20 pool houses in {', '.join(few_pools)}.", ),]print(f"House prices: EDA findings (median sale {median_price:,.0f} USD)")for number, (claim, evidence, caveat) in enumerate(findings, start=1): print(f"{number}. {claim}") print(f" Evidence: {evidence}") print(f" Caveat: {caveat}")House prices: EDA findings (median sale 376,000 USD)1. Size and school rating have the strongest association with price. Evidence: Spearman 0.68 (sqft), 0.68 (school rating), 3,000 sales; sqft 0.53-0.87 per area. Caveat: sqft, bedrooms, bathrooms overlap (rho 0.81-0.87): one signal, not three.2. The price level differs strongly by neighborhood. Evidence: Median price ranges from 249,000 (Cedar Park) to 777,000 (Lakeview), x3.1. Caveat: Neighborhoods differ in size and age mix too; compare per sqft.3. The pool premium is far smaller than the raw gap suggests. Evidence: Raw median gap +78%; per sqft within a neighborhood +5% to +12%. Caveat: Observational; under 20 pool houses in Downtown, Old Town, Westfield.Each finding is one plain claim, one line of numbers with their source, and one honest limit. A manager can act on the claims. An analyst can check the evidence. The caveats say what to look at next.
Common mistakes:
- Typing numbers into the report by hand. They go stale with the next data refresh.
- Writing evidence without the method (“rho = 0.68” says nothing without “Spearman, 3,000 sales”).
- Leaving out the caveat because it “weakens” the finding. A finding without limits is the one that gets misused.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Reporting the mean of a skewed column as “typical” | The “typical” house costs more than 60% of houses | Report the median and a quantile range |
df.corr() on a table with text columns |
ValueError: could not convert string to float |
df.corr(numeric_only=True) or select the columns |
| Trusting a correlation near 0 | A U-shaped pattern (age and churn) is dropped | Bin the feature with pd.cut and compare group means |
| Pearson on data with an extreme point | One row moves r by about 0.08 |
Plot; compare with Spearman; recompute without the point |
| A rate without its count | 0% or 100% churn in a group of 1 | Use .agg(["mean", "size"]); merge rare levels |
crosstab(..., normalize="columns") for a per-group rate |
Shares that answer the wrong question | Groups in the rows, outcome in the columns, normalize="index" |
| Pooling groups with different baselines | Simpson’s paradox: the pooled trend has the wrong sign | Repeat the analysis inside each level of the suspected confounder |
| “X correlates with Y, so X causes Y” | Pool premium of 78% | Compare like with like; state the confounders in the caveat |
value_counts() hides missing values |
Shares that ignore the blanks | value_counts(dropna=False) |
| EDA on the full data before a model split | Optimistic test scores | Split first; explore the training part only |
| Reading a cap as a real value | “Many customers have exactly 72 months” | Check pile-ups at the min and max; label them “72 or more” |
| A pairplot of every column and every row | Slow, unreadable grid | Sample a few hundred rows; pick 4–5 columns |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web and product analytics: before an A/B test, a product team checks the traffic split (target balance), the device mix (
value_counts(normalize=True)) and outlier sessions, the same checklist as here. - Operations and monitoring: site reliability engineers report request latency as p50, p95 and p99 quantiles, because latency is right-skewed and the mean hides the slow tail.
- Data engineering: pipeline tools run profiling checks on every load: row counts, missing shares, key uniqueness and value ranges. The EDA checklist is the manual version of those data-quality tests.
- Finance and business reporting: auditors and analysts write findings with evidence and caveats, and they separate “correlated” from “caused by” before a decision.
Summary
Section titled “Summary”- EDA is the open-ended first look at data. It moves from one variable (univariate) to two (bivariate) to many (multivariate), and each finding raises the next question.
- Describe a numeric column by center, spread and shape. For skewed data, report the median and quantiles, and look at the log scale.
- Describe a category with
value_counts(normalize=True), its number of levels and its rare levels. The target’s shares give the baseline. - Pick the bivariate tool by type: scatter and correlation for two numbers, grouped statistics for a number by a category, a normalized
crosstabfor two categories. - Pearson measures straight-line association and is sensitive to outliers. Spearman uses ranks and measures monotonic association. Neither sees a U-shape.
- Correlation can be broken by outliers, curves, small groups, confounders and Simpson’s paradox. It never proves causation.
- Run the checklist on every table: types, missing values, duplicates, ranges, categories, target balance, leakage suspects.
- Write each finding as claim → evidence → caveat, and compute every number in code.
Self-check questions
Section titled “Self-check questions”Q1. A column has mean 476k and median 376k. What does that tell you about its shape, and which number do you report as typical?
Answer
The mean is far above the median, so the distribution is right-skewed: a long tail of large values pulls the mean up. Report the median as the typical value, with a quantile range such as Q1–Q3.
Q2. What is the difference between Pearson and Spearman correlation? Give one situation where you prefer Spearman.
Answer
Pearson measures how close the points are to a straight line, on the raw values. Spearman computes Pearson on the ranks, so it measures any monotonic relationship. Prefer Spearman when the data are skewed, have outliers or are ordinal scores, for example house prices against school ratings.
Q3. The Pearson correlation between age and churn is −0.04. Can you conclude that age does not matter?
Answer
No. Pearson only sees linear patterns. Churn is high for the youngest and the oldest customers and low in the middle (a U-shape), so the two halves cancel. Bin age with pd.cut and compare the churn rate per band.
Q4. You want “the share of churners among month-to-month customers”. Which crosstab call gives it?
Answer
pd.crosstab(customers["contract"], customers["churned"], normalize="index"), then read column 1 of the month-to-month row. With normalize="index", each row adds up to 1, so each row is the outcome mix of one group.
Q5. Across all houses, lot size and price correlate negatively. Inside each neighborhood, they correlate positively. What is this called, and what causes it?
Answer
Simpson’s paradox. A confounder, the neighborhood, is linked to both variables. The two outer neighborhoods have the biggest lots and the lowest prices; the other areas have smaller lots and higher prices. Pooling lets the cheap big-lot areas pull the overall trend negative, although no single neighborhood has a negative trend.
Q6. A group of customers with 8 support tickets shows a churn rate of 100%. What do you check before you report it?
Answer
The group size. In the course data that group has one customer, so the rate is noise. Show counts next to rates and merge rare levels (for example “5+ tickets”).
Q7. Name three columns that are leakage suspects in a model that predicts price from a house listing, and why.
Answer
price_per_sqft, if someone adds it: it is computed from the target, so it cannot exist before the price is known.sold_date, when you predict at listing time: the sale date is known only after the sale.house_id: the file is sorted bysold_dateand the ids follow that order, so the id encodes the sale time and the market trend.
Confirm with the data owner when each column is filled.
Q8. Why does a box plot fit “compare tenure for churners and non-churners” better than two histograms?
Answer
A box plot shows the median, the quartiles and the outliers of each group side by side on one axis, so the comparison is immediate. Two histograms need two panels and a careful look at different heights and bin counts.
Q9. Rewrite this finding in the claim → evidence → caveat form: “Pools matter a lot.”
Answer
Claim: “Houses with a pool sell for more, but much less than the raw gap suggests.” Evidence: “Raw median gap +78%; within a neighborhood, per square foot, about +5% to +12%.” Caveat: “Observational data; pool houses are larger and in pricier areas, and some neighborhoods have only a few pool houses.”
Q10. Why should EDA for a predictive model use only the training data?
Answer
Every decision you take during EDA (which features to keep, how to bin, which rows to drop) uses what you saw. If you saw the test set, those decisions carry test information into the model, and the test score becomes too optimistic.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 28 exercises on distributions, correlation, crosstabs, the checklist and written findings.
- Mini-project: an EDA brief on customer churn for a retention team.
- Cheat sheet: every EDA call of this module on one page.
- Next module: 28. Visualization teaches Matplotlib, Seaborn and Plotly in depth, and how to choose the right chart for a finding.