Skip to content

24. pandas fundamentals — Mini-project

You work with the retention team of a subscription business. Every Monday, the team calls the customers who are most likely to cancel. Today, an analyst builds that call list by hand in a spreadsheet. It takes an hour and the rules change from week to week.

Write a script, watch_list.py, that builds the list from data/customers.csv in one run. It scores each customer with simple, documented rules, checks that the score really separates churners from loyal customers, and saves the list for the team. The script must run with one command, python watch_list.py, so that it can run every week on a fresh export.

The project uses every part of module 24: typed loading with read_csv, inspection, ordered categoricals, vectorized columns, np.select, boolean filtering, loc, multi-key sorting and CSV and Parquet output.

data/customers.csv has 5,000 subscription customers and a snapshot date of 2024-12-31. One row is one customer. The columns this project needs:

Column Meaning
customer_id C00001..C05000
region North, South, East, West
plan basic, standard, premium (in that order of price)
contract month-to-month, one-year, two-year (in that order of commitment)
payment_method electronic_check, credit_card, bank_transfer, paypal
has_autopay 1 if the customer pays automatically, else 0
tenure_months months since signup, 0–72
monthly_charges the monthly bill in USD
support_tickets support tickets in the last period, 0–9
logins_last_30d logins in the last 30 days, 0–60
churned 1 if the customer cancelled in the last month

total_charges is blank for 10 brand-new customers. The overall churn rate is 19.3%.

Start your script with the course setup block:

from pathlib import Path
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)

Your script must:

  1. Load the file with read_csv and set the dtypes at load time: signup_date as a date, region and payment_method as category, and plan and contract as ordered categoricals in the business order given in the dataset table.

  2. Print the shape, the columns that have gaps with their counts, and the overall churn rate.

  3. Compute an integer risk_score per customer with vectorized arithmetic (no apply, no loop over rows). Add the points of every rule that holds:

    Rule Points
    month-to-month contract 2
    tenure of 6 months or less 2
    3 logins or fewer in 30 days 1
    4 support tickets or more 1
    pays by electronic check without autopay 1
  4. Turn the score into a risk_level column with np.select: high for a score of 4 or more, medium for 2 or 3, low otherwise. Store it as an ordered categorical (low < medium < high).

  5. Validate the score: for each risk level, print the number of customers and their churn rate. The churn rate must rise from low to high.

  6. Build the watch list: customers who have not churned and whose level is high. Sort by risk_score (high to low), then monthly_charges (high to low), then customer_id, and give the result a fresh 0, 1, 2… index.

  7. Print the size of the list, the monthly revenue at risk (the sum of monthly_charges on the list), the first 10 rows (7 columns, see the report) and the number of listed customers per region.

  8. Save the 7 report columns to output/watch_list.csv and the full list to output/watch_list.parquet, both without the index. Read the Parquet file back and print whether it equals the list.

  9. Explain each rule and each non-obvious line with a comment.

The expected report:

Expected output
Customers: (5000, 15)
Columns with gaps: {'total_charges': 10}
Churn rate: 19.3%
Churn rate by risk level:
low 2057 customers, churn 5.7%
medium 1868 customers, churn 17.6%
high 1075 customers, churn 48.0%
Watch list: 559 active customers
Monthly revenue at risk: 31,750.12 USD
customer_id region plan contract tenure_months monthly_charges risk_score
0 C04663 South standard month-to-month 2 73.73 6
1 C04207 North standard month-to-month 4 65.37 6
2 C04055 West basic month-to-month 5 62.96 6
3 C03931 East basic month-to-month 6 44.53 6
4 C04262 North basic month-to-month 4 44.03 6
5 C04225 North basic month-to-month 4 38.88 6
6 C04371 North basic month-to-month 4 38.50 6
7 C04755 West basic month-to-month 1 38.45 6
8 C04555 North basic month-to-month 2 35.54 6
9 C04136 South premium month-to-month 5 106.20 5
Listed per region: {'East': 166, 'North': 143, 'South': 143, 'West': 107}
Parquet keeps dtypes: True
  1. Define the dtypes. Create the three ordered pd.CategoricalDtype objects (plan, contract, risk level) at the top of the script as constants. Constants in UPPER_CASE tell the reader that these values never change.

  2. Load and inspect. Pass parse_dates and a dtype dict to read_csv. Print customers.dtypes once to check, then remove that line. Count gaps with isna().sum() and keep the entries above 0.

  3. Score. Each rule is a boolean Series. True counts as 1 in arithmetic, so 2 * (customers["contract"] == "month-to-month") gives 2 or 0 per row. Add the five terms.

  4. Level. np.select([score >= 4, score >= 2], ["high", "medium"], default="low") returns a NumPy array. Wrap it in a Series with the customers’ index, then astype the ordered level dtype.

  5. Validate. Loop over the three levels (3 iterations, not 5,000). For each level, build a mask and take the mean of churned with loc.

  6. Filter and sort. Combine two masks with &. Sort with three keys and a list of three directions. reset_index(drop=True) renumbers the rows.

  7. Report and save. Print with f-strings. Use value_counts().to_dict() for a one-line region summary. Create output/ with Path("output").mkdir(exist_ok=True) before you write.

  8. Run it with python watch_list.py. Compare every line with the expected report.

A skeleton to start from:

watch_list.py (starter)
# watch_list.py: weekly churn-risk watch list for the retention team.
from pathlib import Path
import numpy as np
import pandas as pd
# TODO: display options
# --- Dtypes ---
# TODO: PLAN, CONTRACT and LEVEL as ordered CategoricalDtype objects
# --- Load and inspect ---
# TODO: read_csv with parse_dates and dtype; print shape, gaps, churn rate
# --- Score ---
# TODO: five boolean rules, weighted and added; np.select for the level
# --- Validate ---
# TODO: customers and churn rate per level
# --- Watch list ---
# TODO: filter, sort with three keys, reset the index, print, save, read back
Criterion Points Full points when
Runs as a script 2 python watch_list.py runs with no error and no warning
Typed loading 3 Dates, categoricals and both ordered categoricals are set in read_csv
Vectorized score 3 The score uses column arithmetic only: no apply, no row loop
Risk level 2 np.select and an ordered categorical; levels sort as low < medium < high
Validation 2 Churn rate per level is printed and rises from low to high
Filter and sort 2 Masks combined with &; three sort keys with the right directions; fresh index
Output files 2 CSV and Parquet in output/, no index column; the Parquet check prints True
Readability 2 Named masks and constants; comments explain the rules and the reasons
Total 18 15 or more: you are ready for module 25
  1. Add a column expected_loss: the monthly charges times the churn rate of the customer’s risk level. Sort the watch list by it instead of the score, and compare the top 10.
  2. Write the watch list to an Excel workbook with one sheet per region. pd.ExcelWriter("output/watch_list.xlsx") used in a with block lets you call to_excel(writer, sheet_name=region) several times.
  3. Read the score threshold for high from the command line with argparse (module 08), with a default of 4.
  4. Save the list as CSV too and read it back. Print which dtypes CSV loses compared with Parquet.
  5. Measure the memory of the loaded frame with and without the dtype argument, as in exercise M24-X05.

Try the project yourself first. Then compare your script with this one. Your names and comments can differ; your output must not.

Reference solution
watch_list.py
# watch_list.py: weekly churn-risk watch list for the retention team.
# Input: data/customers.csv. Output: output/watch_list.csv and .parquet.
from pathlib import Path
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)
# --- Dtypes: business order, not alphabetical order --------------------
PLAN = pd.CategoricalDtype(["basic", "standard", "premium"], ordered=True)
CONTRACT = pd.CategoricalDtype(["month-to-month", "one-year", "two-year"], ordered=True)
LEVEL = pd.CategoricalDtype(["low", "medium", "high"], ordered=True)
REPORT_COLS = [
"customer_id",
"region",
"plan",
"contract",
"tenure_months",
"monthly_charges",
"risk_score",
]
# --- Load and inspect ---------------------------------------------------
customers = pd.read_csv(
"data/customers.csv",
parse_dates=["signup_date"],
dtype={
"region": "category",
"payment_method": "category",
"plan": PLAN,
"contract": CONTRACT,
},
)
missing = customers.isna().sum()
print("Customers:", customers.shape)
print("Columns with gaps:", missing[missing > 0].to_dict())
print(f"Churn rate: {customers['churned'].mean():.1%}")
# --- Score: each rule is a boolean Series; True counts as 1 -------------
monthly = customers["contract"] == "month-to-month" # no commitment: easy to leave
new = customers["tenure_months"] <= 6 # first months: highest churn
inactive = customers["logins_last_30d"] <= 3 # customers who stopped using it
unhappy = customers["support_tickets"] >= 4 # repeated problems
manual_check = (customers["payment_method"] == "electronic_check") & (
customers["has_autopay"] == 0
) # every bill is a decision to pay again
score = 2 * monthly + 2 * new + inactive + unhappy + manual_check
level = np.select([score >= 4, score >= 2], ["high", "medium"], default="low")
customers = customers.assign(
risk_score=score,
risk_level=pd.Series(level, index=customers.index).astype(LEVEL),
)
# --- Validate on all customers: churn must rise with the level ----------
print("Churn rate by risk level:")
for name in LEVEL.categories: # 3 iterations, one per level
in_level = customers["risk_level"] == name
rate = customers.loc[in_level, "churned"].mean()
print(f" {name:<6} {in_level.sum():>5} customers, churn {rate:.1%}")
# --- Watch list: still active, high risk, most urgent first -------------
active_high = (customers["churned"] == 0) & (customers["risk_level"] == "high")
watch = (
customers.loc[active_high]
.sort_values(
["risk_score", "monthly_charges", "customer_id"],
ascending=[False, False, True],
)
.reset_index(drop=True)
)
print(f"Watch list: {len(watch)} active customers")
print(f"Monthly revenue at risk: {watch['monthly_charges'].sum():,.2f} USD")
print(watch[REPORT_COLS].head(10))
print("Listed per region:", watch["region"].value_counts().to_dict())
# --- Save: CSV for the team, Parquet for the next pipeline step ---------
Path("output").mkdir(exist_ok=True)
watch[REPORT_COLS].to_csv("output/watch_list.csv", index=False)
watch.to_parquet("output/watch_list.parquet", index=False)
back = pd.read_parquet("output/watch_list.parquet")
print("Parquet keeps dtypes:", back.equals(watch))
# --- Self-checks ---------------------------------------------------------
assert watch["risk_score"].is_monotonic_decreasing
assert (watch["churned"] == 0).all()
assert len(pd.read_csv("output/watch_list.csv")) == len(watch)
Output
Customers: (5000, 15)
Columns with gaps: {'total_charges': 10}
Churn rate: 19.3%
Churn rate by risk level:
low 2057 customers, churn 5.7%
medium 1868 customers, churn 17.6%
high 1075 customers, churn 48.0%
Watch list: 559 active customers
Monthly revenue at risk: 31,750.12 USD
customer_id region plan contract tenure_months monthly_charges risk_score
0 C04663 South standard month-to-month 2 73.73 6
1 C04207 North standard month-to-month 4 65.37 6
2 C04055 West basic month-to-month 5 62.96 6
3 C03931 East basic month-to-month 6 44.53 6
4 C04262 North basic month-to-month 4 44.03 6
5 C04225 North basic month-to-month 4 38.88 6
6 C04371 North basic month-to-month 4 38.50 6
7 C04755 West basic month-to-month 1 38.45 6
8 C04555 North basic month-to-month 2 35.54 6
9 C04136 South premium month-to-month 5 106.20 5
Listed per region: {'East': 166, 'North': 143, 'South': 143, 'West': 107}
Parquet keeps dtypes: True

Run it from the project folder:

Terminal
python watch_list.py

How it works:

  1. Dtypes. The three ordered categoricals encode business knowledge: a two-year contract is “more committed” than a one-year contract. read_csv applies them while it parses, so the frame never holds the plain text.
  2. Inspect. isna().sum() filtered with > 0 reports only the columns with gaps. to_dict() prints a Series on one line.
  3. Score. Each rule is a named boolean Series. In arithmetic, True is 1 and False is 0, so 2 * monthly gives 2 or 0 points per row. Adding five Series computes all 5,000 scores at once. The first term is already an integer Series, so every later + gives integers too. Start with an integer term: in NumPy, True + True on two boolean arrays is a logical or, not 2.
  4. Level. np.select takes the first condition that holds per row: a score of 5 matches >= 4 first and gets high. The ordered dtype makes value_counts(sort=False), sorting and >= follow low < medium < high.
  5. Validation. Churn rises from 5.7% to 17.6% to 48.0%. The score separates customers well, so the list is worth the team’s time. Without this check, a list is a guess.
  6. Watch list. The mask keeps active, high-risk customers. The sort puts the highest score first; among equal scores, the biggest bill first; the id breaks the remaining ties, so the order is the same every week. reset_index(drop=True) gives the list 0, 1, 2… row numbers.
  7. Save. CSV is for people and spreadsheets. Parquet keeps the categoricals and the date, so equals is True and the next script can load the list without any dtype arguments.

Alternative: module 25 replaces the validation loop with one line, customers.groupby("risk_level", observed=True)["churned"].agg(["size", "mean"]). A machine-learning model (module 36) can learn the weights from the data instead of fixing them by hand. The rule-based score stays useful: everyone on the team can read and explain it.