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.
Dataset
Section titled “Dataset”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 npimport pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)Requirements
Section titled “Requirements”Your script must:
-
Load the file with
read_csvand set the dtypes at load time:signup_dateas a date,regionandpayment_methodascategory, andplanandcontractas ordered categoricals in the business order given in the dataset table. -
Print the shape, the columns that have gaps with their counts, and the overall churn rate.
-
Compute an integer
risk_scoreper customer with vectorized arithmetic (noapply, 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 -
Turn the score into a
risk_levelcolumn withnp.select:highfor a score of 4 or more,mediumfor 2 or 3,lowotherwise. Store it as an ordered categorical (low < medium < high). -
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.
-
Build the watch list: customers who have not churned and whose level is
high. Sort byrisk_score(high to low), thenmonthly_charges(high to low), thencustomer_id, and give the result a fresh 0, 1, 2… index. -
Print the size of the list, the monthly revenue at risk (the sum of
monthly_chargeson the list), the first 10 rows (7 columns, see the report) and the number of listed customers per region. -
Save the 7 report columns to
output/watch_list.csvand the full list tooutput/watch_list.parquet, both without the index. Read the Parquet file back and print whether it equals the list. -
Explain each rule and each non-obvious line with a comment.
The expected report:
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 customersMonthly revenue at risk: 31,750.12 USD customer_id region plan contract tenure_months monthly_charges risk_score0 C04663 South standard month-to-month 2 73.73 61 C04207 North standard month-to-month 4 65.37 62 C04055 West basic month-to-month 5 62.96 63 C03931 East basic month-to-month 6 44.53 64 C04262 North basic month-to-month 4 44.03 65 C04225 North basic month-to-month 4 38.88 66 C04371 North basic month-to-month 4 38.50 67 C04755 West basic month-to-month 1 38.45 68 C04555 North basic month-to-month 2 35.54 69 C04136 South premium month-to-month 5 106.20 5Listed per region: {'East': 166, 'North': 143, 'South': 143, 'West': 107}Parquet keeps dtypes: TrueStep plan
Section titled “Step plan”-
Define the dtypes. Create the three ordered
pd.CategoricalDtypeobjects (plan, contract, risk level) at the top of the script as constants. Constants in UPPER_CASE tell the reader that these values never change. -
Load and inspect. Pass
parse_datesand adtypedict toread_csv. Printcustomers.dtypesonce to check, then remove that line. Count gaps withisna().sum()and keep the entries above 0. -
Score. Each rule is a boolean Series.
Truecounts as 1 in arithmetic, so2 * (customers["contract"] == "month-to-month")gives 2 or 0 per row. Add the five terms. -
Level.
np.select([score >= 4, score >= 2], ["high", "medium"], default="low")returns a NumPy array. Wrap it in a Series with the customers’ index, thenastypethe ordered level dtype. -
Validate. Loop over the three levels (3 iterations, not 5,000). For each level, build a mask and take the mean of
churnedwithloc. -
Filter and sort. Combine two masks with
&. Sort with three keys and a list of three directions.reset_index(drop=True)renumbers the rows. -
Report and save. Print with f-strings. Use
value_counts().to_dict()for a one-line region summary. Createoutput/withPath("output").mkdir(exist_ok=True)before you write. -
Run it with
python watch_list.py. Compare every line with the expected report.
A skeleton to start from:
# watch_list.py: weekly churn-risk watch list for the retention team.from pathlib import Path
import numpy as npimport 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 backRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- 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. - Write the watch list to an Excel workbook with one sheet per region.
pd.ExcelWriter("output/watch_list.xlsx")used in awithblock lets you callto_excel(writer, sheet_name=region)several times. - Read the score threshold for
highfrom the command line withargparse(module 08), with a default of 4. - Save the list as CSV too and read it back. Print which dtypes CSV loses compared with Parquet.
- Measure the memory of the loaded frame with and without the
dtypeargument, as in exercise M24-X05.
Reference solution
Section titled “Reference solution”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: 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 npimport 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 leavenew = customers["tenure_months"] <= 6 # first months: highest churninactive = customers["logins_last_30d"] <= 3 # customers who stopped using itunhappy = customers["support_tickets"] >= 4 # repeated problemsmanual_check = (customers["payment_method"] == "electronic_check") & ( customers["has_autopay"] == 0) # every bill is a decision to pay againscore = 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_decreasingassert (watch["churned"] == 0).all()assert len(pd.read_csv("output/watch_list.csv")) == len(watch)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 customersMonthly revenue at risk: 31,750.12 USD customer_id region plan contract tenure_months monthly_charges risk_score0 C04663 South standard month-to-month 2 73.73 61 C04207 North standard month-to-month 4 65.37 62 C04055 West basic month-to-month 5 62.96 63 C03931 East basic month-to-month 6 44.53 64 C04262 North basic month-to-month 4 44.03 65 C04225 North basic month-to-month 4 38.88 66 C04371 North basic month-to-month 4 38.50 67 C04755 West basic month-to-month 1 38.45 68 C04555 North basic month-to-month 2 35.54 69 C04136 South premium month-to-month 5 106.20 5Listed per region: {'East': 166, 'North': 143, 'South': 143, 'West': 107}Parquet keeps dtypes: TrueRun it from the project folder:
python watch_list.pyHow it works:
- Dtypes. The three ordered categoricals encode business knowledge: a two-year contract is “more committed” than a one-year contract.
read_csvapplies them while it parses, so the frame never holds the plain text. - Inspect.
isna().sum()filtered with> 0reports only the columns with gaps.to_dict()prints a Series on one line. - Score. Each rule is a named boolean Series. In arithmetic,
Trueis 1 andFalseis 0, so2 * monthlygives 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 + Trueon two boolean arrays is a logical or, not 2. - Level.
np.selecttakes the first condition that holds per row: a score of 5 matches>= 4first and getshigh. The ordered dtype makesvalue_counts(sort=False), sorting and>=followlow < medium < high. - 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.
- 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. - Save. CSV is for people and spreadsheets. Parquet keeps the categoricals and the date, so
equalsisTrueand the next script can load the list without anydtypearguments.
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.