Skip to content

27. Exploratory data analysis — Mini-project

A subscription business loses about one customer in five every month. The retention team wants to call the customers most likely to leave, but first it asks three questions:

  1. Can we trust the customer table?
  2. Which customers churn most, and how much more than average?
  3. Which of these patterns are solid, and which could mislead us?

Write a script, churn_eda.py, that answers them. It runs the EDA checklist, profiles the columns, compares churn across every relevant feature, looks at two features at a time, checks the correlation traps and prints a findings report. Every number in the report must come from the code.

The project uses every part of module 27: the checklist, univariate profiles, rates with sizes and lifts, binned numeric features, two-key pivot tables, Pearson against Spearman, confounding and written findings.

data/customers.csv: 5,000 subscription customers, snapshot at the end of 2024, one row per customer.

Column Meaning
customer_id key, C00001..C05000, increases with the signup date
signup_date date of the first subscription (text)
age, region customer profile
plan, contract, payment_method, has_autopay subscription settings
tenure_months months as a customer, capped at 72
monthly_charges, total_charges billing; total_charges is blank for 10 brand-new customers
support_tickets, logins_last_30d, avg_session_minutes usage
churned target: 1 if the customer left in the last month

Your script must:

  1. Checklist: print the shape, the dtype counts, the columns with missing values (and why they are missing), the number of duplicate rows, whether customer_id is unique, the churn rate and at least one leakage or redundancy suspect.
  2. Univariate: print a table with the median, the mean and the skew of the numeric features, and the shares of each level of contract, plan and payment_method.
  3. Bivariate: print the churn rate, size and lift for every level of contract, payment_method, plan, has_autopay and region. Print the same for binned tenure_months, logins_last_30d, age and for support_tickets with 5 or more merged.
  4. Multivariate: print two pivot tables of the churn rate: contract × tenure band, and contract × support tickets (0 to 4+). Print the tenure-band mix of each contract type.
  5. Correlation check: print Pearson and Spearman of each numeric feature with churned, and name one feature where the correlation alone misleads.
  6. Findings: print at least five findings, each with a claim, evidence (numbers computed in the script) and a caveat.
  7. Run in under 60 seconds and print no warnings.

Each finding follows this shape:

Finding format
1. <Claim: one plain sentence a manager can act on>
Evidence: <numbers, group sizes and the method>
Caveat: <what the evidence does not show>
  1. Load and check. Read the CSV. Run checks 1–7 of the lesson’s checklist. Decide what the 10 blank total_charges mean before you go on.

  2. Profile one column at a time. Build the numeric table with agg(["median", "mean", "skew"]). Use value_counts(normalize=True) for the categories.

  3. Write one helper. A function rate_table(df, keys) that returns rate, size and lift saves you from repeating the same groupby ten times.

  4. Compare churn across features. Call the helper for each category. Bin the numeric features with pd.cut and call it again. Merge rare ticket counts.

  5. Look at two features at a time. Build the two pivot tables. Ask: does the contract gap hold inside each tenure band? Does the ticket pattern appear for every contract type?

  6. Check the correlation traps. Compute both coefficients. Compare them with the binned rates. Which feature has a strong pattern but a tiny correlation?

  7. Write the findings. Pick the five most useful patterns. For each one, compute the evidence into variables, then print claim, evidence and caveat with f-strings.

Criterion Excellent Adequate Missing
Checklist All seven checks; the missing values explained; at least one leakage or redundancy suspect with a reason Most checks; missing values counted but not explained No checklist, or analysis on unchecked data
Univariate profile Numeric table with median, mean and skew; category shares; the right center chosen for skewed columns Some columns profiled No profile
Bivariate rates Rate, size and lift for every feature; numeric features binned; rare groups merged Rates without sizes or lifts Only correlations, or rates from groups of 1
Multivariate Both pivots, with the interaction and the confounding named One pivot None
Correlation traps Pearson and Spearman shown; one misleading correlation identified with evidence Coefficients shown, not discussed Correlation used as the only evidence
Findings Five findings, each claim → evidence → caveat; every number computed Findings without caveats, or with typed-in numbers No written findings
Code quality One helper, clear names, no repeated blocks, no warnings Some repetition Copy-pasted blocks, warnings
  • Draw the contract × tenure-band pivot as a heatmap with sns.heatmap(..., annot=True). Module 28 covers styling.
  • Split the data with train_test_split(test_size=0.25, stratify=customers["churned"], random_state=42) first, and run the whole EDA on the training part only. Check that the findings still hold.
  • Write the report to output/churn_findings.md as a Markdown list, so the retention team can paste it into a wiki.
  • Turn the helper and the binning into the ChurnExplorer class from exercise M27-X05.

Try the project yourself first. The reference solution is one possible answer. It runs as one script from top to bottom.

Reference solution

Part 1: load and run the checklist.

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)
customers = pd.read_csv("data/customers.csv")
print("shape:", customers.shape)
print("dtypes:", customers.dtypes.astype(str).value_counts().to_dict())
missing = customers.isna().sum()
print("missing:", missing[missing > 0].to_dict())
blank_tenure = customers.loc[customers["total_charges"].isna(), "tenure_months"]
print("tenure of rows with blank total_charges:", blank_tenure.unique().tolist())
print("duplicate rows:", customers.duplicated().sum())
print("customer_id unique:", customers["customer_id"].is_unique)
base_rate = customers["churned"].mean()
print(f"churn rate: {base_rate:.2%}")
tenure, total = customers["tenure_months"], customers["total_charges"]
rho_total = tenure.corr(total, method="spearman")
print(f"redundancy suspect: rho(tenure_months, total_charges) = {rho_total:.3f}")
print(customers.describe().T[["min", "max"]].round(2))
tenure_counts = customers["tenure_months"].value_counts().sort_index()
print("tenure 68-72:", tenure_counts.tail(5).to_dict())
print(customers.select_dtypes("str").nunique())
Output
shape: (5000, 15)
dtypes: {'str': 6, 'int64': 6, 'float64': 3}
missing: {'total_charges': 10}
tenure of rows with blank total_charges: [0]
duplicate rows: 0
customer_id unique: True
churn rate: 19.26%
redundancy suspect: rho(tenure_months, total_charges) = 0.936
min max
age 18.00 80.00
has_autopay 0.00 1.00
tenure_months 0.00 72.00
monthly_charges 28.05 143.24
total_charges 29.55 8322.61
support_tickets 0.00 9.00
logins_last_30d 0.00 60.00
avg_session_minutes 1.00 68.10
churned 0.00 1.00
tenure 68-72: {68: 9, 69: 10, 70: 16, 71: 11, 72: 220}
customer_id 5000
signup_date 1542
region 4
plan 3
contract 3
payment_method 4
dtype: int64

The table is clean: one row per customer, no duplicates, gaps only for the 10 customers with tenure 0. Every range is plausible, but 220 customers sit at tenure 72 against 9 to 16 at 68–71: 72 is a cap, so read it as “72 or more”. The category columns have 3 or 4 levels each, with no spelling variants. The churn rate is the base rate for every lift below. total_charges mostly repeats tenure, and customer_id encodes the signup order, so neither belongs in a model as is.

Part 2: profile each column.

numeric = [
"age", "tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "avg_session_minutes",
]
profile = customers[numeric].agg(["median", "mean", "skew"]).T
print(profile.round(2))
for column in ["contract", "plan", "payment_method"]:
shares = customers[column].value_counts(normalize=True)
print(f"{column}: " + ", ".join(f"{level} {s:.1%}" for level, s in shares.items()))
Output
median mean skew
age 42.00 42.26 0.16
tenure_months 17.00 23.08 1.02
monthly_charges 58.86 60.84 0.62
support_tickets 1.00 1.24 1.04
logins_last_30d 10.00 11.74 1.72
avg_session_minutes 12.90 14.34 1.27
contract: month-to-month 55.7%, one-year 24.5%, two-year 19.8%
plan: basic 40.6%, standard 39.6%, premium 19.8%
payment_method: electronic_check 31.3%, credit_card 27.2%, bank_transfer 24.2%, paypal 17.4%

Every usage and tenure column is right-skewed, so medians describe them better than means. More than half of the customers are on month-to-month contracts.

Part 3: rates, sizes and lifts for each feature.

def rate_table(df: pd.DataFrame, keys) -> pd.DataFrame:
"""Churn rate, group size and lift for any groupby keys."""
table = df.groupby(keys, observed=True)["churned"].agg(rate="mean", size="size")
table["lift"] = table["rate"] / df["churned"].mean()
return table
categorical = ["contract", "payment_method", "plan", "has_autopay", "region"]
rates = pd.concat({column: rate_table(customers, column) for column in categorical})
rates.index.names = ["feature", "level"]
print(rates.round(3))
Output
rate size lift
feature level
contract month-to-month 0.296 2784 1.535
one-year 0.088 1225 0.458
two-year 0.032 991 0.168
payment_method bank_transfer 0.174 1209 0.902
credit_card 0.158 1360 0.821
electronic_check 0.248 1563 1.286
paypal 0.174 868 0.903
plan basic 0.174 2028 0.901
premium 0.296 990 1.537
standard 0.160 1982 0.833
has_autopay 0 0.219 2355 1.135
1 0.169 2645 0.879
region East 0.193 1416 1.001
North 0.205 1225 1.064
South 0.178 1268 0.925
West 0.195 1091 1.014

pd.concat with a dict stacks the five tables and adds the feature name as an outer index level. Contract has by far the widest spread of lifts (0.17 to 1.54). Region hardly matters.

Part 4: binned numeric features.

bands = {
"tenure": pd.cut(
customers["tenure_months"], [-1, 6, 24, 72], labels=["0-6", "7-24", "25-72"]
),
"logins": pd.cut(
customers["logins_last_30d"], [-1, 3, 10, 60], labels=["0-3", "4-10", "11+"]
),
"age": pd.cut(
customers["age"], [17, 25, 55, 65, 80],
labels=["18-25", "26-55", "56-65", "66+"],
),
"tickets": (
customers["support_tickets"].clip(upper=5).astype(str).replace("5", "5+")
),
}
binned = pd.concat({name: rate_table(customers, band) for name, band in bands.items()})
binned.index.names = ["feature", "band"]
print(binned.round(3))
Output
rate size lift
feature band
tenure 0-6 0.440 1110 2.283
7-24 0.164 2049 0.854
25-72 0.075 1841 0.389
logins 0-3 0.425 395 2.208
4-10 0.180 2237 0.935
11+ 0.166 2368 0.860
age 18-25 0.307 502 1.593
26-55 0.169 3727 0.875
56-65 0.195 589 1.014
66+ 0.363 182 1.883
tickets 0 0.132 1537 0.686
1 0.160 1742 0.832
2 0.207 1027 1.077
3 0.326 457 1.693
4 0.473 184 2.455
5+ 0.604 53 3.135

Four shapes appear: a steep fall with tenure, a threshold at 3 logins, a U-shape in age and a steady rise with tickets. The 5+ group merges 53 customers: large enough to report, but with a wide margin of several percentage points.

Part 5: two features at a time.

customers["tenure_band"] = bands["tenure"]
customers["tickets_4plus"] = customers["support_tickets"].clip(upper=4)
by_tenure = customers.pivot_table(
index="contract", columns="tenure_band", values="churned",
aggfunc="mean", observed=True,
)
mix = pd.crosstab(customers["contract"], customers["tenure_band"], normalize="index")
by_tickets = customers.pivot_table(
index="contract", columns="tickets_4plus", values="churned", aggfunc="mean"
)
print("churn rate, contract x tenure band:")
print(by_tenure.round(3))
print("tenure mix of each contract:")
print(mix.round(3))
ticket_sizes = pd.crosstab(customers["contract"], customers["tickets_4plus"])
print("churn rate, contract x tickets (4 = 4 or more):")
print(by_tickets.round(3))
print("customers per cell:")
print(ticket_sizes)
Output
churn rate, contract x tenure band:
tenure_band 0-6 7-24 25-72
contract
month-to-month 0.469 0.220 0.141
one-year 0.188 0.098 0.069
two-year 0.088 0.027 0.032
tenure mix of each contract:
tenure_band 0-6 7-24 25-72
contract
month-to-month 0.362 0.455 0.183
one-year 0.056 0.424 0.520
two-year 0.034 0.264 0.701
churn rate, contract x tickets (4 = 4 or more):
tickets_4plus 0 1 2 3 4
contract
month-to-month 0.205 0.231 0.314 0.495 0.716
one-year 0.080 0.101 0.083 0.092 0.065
two-year 0.019 0.037 0.051 0.025 0.000
customers per cell:
tickets_4plus 0 1 2 3 4
contract
month-to-month 795 966 582 279 162
one-year 425 427 229 98 46
two-year 317 349 216 80 29

The first table shows that the contract gap holds inside every tenure band: in the first six months, 46.9% of month-to-month customers churn against 8.8% on two-year contracts. The mix table shows the confounding: 36.2% of month-to-month customers are in their first six months, against 3.4% of two-year customers. So part of the raw contract gap is a tenure gap. The third table shows an interaction: churn climbs steeply with tickets for month-to-month customers (20.5% at 0 tickets, 71.6% at 4 or more) but not for one-year or two-year customers. The last table gives the caveat: only 46 one-year and 29 two-year customers have 4 or more tickets, so those cells are noisy.

Part 6: the correlation check.

corr = pd.DataFrame(
{
"pearson": customers[numeric].corrwith(customers["churned"]),
"spearman": customers[numeric].corrwith(
customers["churned"], method="spearman"
),
}
)
print(corr.round(3))
Output
pearson spearman
age -0.039 -0.050
tenure_months -0.281 -0.336
monthly_charges 0.122 0.103
support_tickets 0.210 0.178
logins_last_30d -0.096 -0.109
avg_session_minutes -0.052 -0.048

corrwith correlates each column with one Series. Age has the smallest Pearson coefficient of all (−0.039), yet Part 4 shows a strong U-shape: 36.3% churn at 66+ and 30.7% at 18–25, against 16.9% at 26–55. Logins look weak too, but they hide a threshold. A correlation ranking would drop both features.

Part 7: the findings report.

mtm = rates.loc[("contract", "month-to-month")]
two_year = rates.loc[("contract", "two-year")]
new_mtm = by_tenure.loc["month-to-month", "0-6"]
new_two = by_tenure.loc["two-year", "0-6"]
early = binned.loc[("tenure", "0-6")]
late = binned.loc[("tenure", "25-72")]
tickets_mtm = by_tickets.loc["month-to-month"]
tickets_one = by_tickets.loc["one-year"]
sizes_one = ticket_sizes.loc["one-year"]
low_logins = binned.loc[("logins", "0-3")]
old, middle = binned.loc[("age", "66+")], binned.loc[("age", "26-55")]
findings = [
(
"Month-to-month customers churn most, at every tenure.",
f"{mtm['rate']:.1%} vs {two_year['rate']:.1%} on two-year contracts "
f"(n={mtm['size']:.0f}); in months 0-6: {new_mtm:.1%} vs {new_two:.1%}.",
"Customers choose their contract; a forced switch may not cut churn.",
),
(
"The first six months are the danger zone.",
f"{early['rate']:.1%} churn at tenure 0-6 (n={early['size']:.0f}) vs "
f"{late['rate']:.1%} after 24 months.",
"Tenure is capped at 72 and mixes with contract type (see the mix table).",
),
(
"Many support tickets go with churn only on month-to-month contracts.",
f"Month-to-month {tickets_mtm[0]:.1%} at 0, "
f"{tickets_mtm[4]:.1%} at 4+ tickets; "
f"one-year {tickets_one[0]:.1%} (n={sizes_one[0]}), "
f"{tickets_one[4]:.1%} (n={sizes_one[4]}).",
f"Only {sizes_one[4]} one-year customers have 4+ tickets; tickets may "
"follow intent to leave.",
),
(
"Customers with 0-3 logins a month are a clear risk group.",
f"{low_logins['rate']:.1%} churn (n={low_logins['size']:.0f}), "
f"lift {low_logins['lift']:.2f}; Pearson r with logins is only "
f"{corr.loc['logins_last_30d', 'pearson']:.3f}.",
"A 30-day window; one quiet month may be a holiday, not disengagement.",
),
(
"Churn is high at both ends of the age range, which a correlation hides.",
f"{old['rate']:.1%} churn at 66+ (n={old['size']:.0f}) vs "
f"{middle['rate']:.1%} at 26-55; Spearman with age "
f"{corr.loc['age', 'spearman']:.3f}.",
f"The 66+ group has only {old['size']:.0f} customers; recheck next quarter.",
),
]
print(f"Churn EDA: {len(customers):,} customers, base churn rate {base_rate:.1%}")
for number, (claim, evidence, caveat) in enumerate(findings, start=1):
print(f"{number}. {claim}")
print(f" Evidence: {evidence}")
print(f" Caveat: {caveat}")
assert len(findings) >= 5
assert new_mtm > 3 * new_two
Output
Churn EDA: 5,000 customers, base churn rate 19.3%
1. Month-to-month customers churn most, at every tenure.
Evidence: 29.6% vs 3.2% on two-year contracts (n=2784); in months 0-6: 46.9% vs 8.8%.
Caveat: Customers choose their contract; a forced switch may not cut churn.
2. The first six months are the danger zone.
Evidence: 44.0% churn at tenure 0-6 (n=1110) vs 7.5% after 24 months.
Caveat: Tenure is capped at 72 and mixes with contract type (see the mix table).
3. Many support tickets go with churn only on month-to-month contracts.
Evidence: Month-to-month 20.5% at 0, 71.6% at 4+ tickets; one-year 8.0% (n=425), 6.5% (n=46).
Caveat: Only 46 one-year customers have 4+ tickets; tickets may follow intent to leave.
4. Customers with 0-3 logins a month are a clear risk group.
Evidence: 42.5% churn (n=395), lift 2.21; Pearson r with logins is only -0.096.
Caveat: A 30-day window; one quiet month may be a holiday, not disengagement.
5. Churn is high at both ends of the age range, which a correlation hides.
Evidence: 36.3% churn at 66+ (n=182) vs 16.9% at 26-55; Spearman with age -0.050.
Caveat: The 66+ group has only 182 customers; recheck next quarter.

How it works:

  1. Parts 1 and 2 are the checklist and the univariate profile. They decide how to treat the blanks (structural, tenure 0) and which centers to report (medians).
  2. One helper, rate_table, produces every rate table. pd.concat with a dict turns many small tables into one, with the feature as an index level, so loc[("contract", "two-year")] reads any cell.
  3. The pivots in Part 5 test each pattern against a second variable. The contract gap holds inside tenure bands, so it is not only a tenure gap. The ticket pattern lives in one contract type only.
  4. Part 6 shows why correlation alone fails here: age and logins have strong but non-linear patterns.
  5. Part 7 computes every number into a variable before it prints a sentence. The caveats name the main risks: self-selection into contracts, a capped variable, reverse causation, a short window and a small group.