Mathew K Analytics

Lesson 23 · Real-World Data Analytics

Customer Churn Analysis in Python: Telco Dataset | Data Analytics #23

Which customers are about to leave, and why? We analyse real telecom customer churn in pandas: churn by contract type, payment method, tenure and services,…

What you'll learn

Datasets used in this lesson

Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.

📓 Full notebook

Download .ipynb

Data Analytics 100, Video 23: Real Customer Churn and Retention Analysis#

  • Video twenty-three of the hundred-video real-world data analytics series.
  • Real genuine telecom customer records, hunting for exactly which real customers are most likely to leave.
  • Let's get into it.

This lesson is for learners who can group and filter data in pandas and want to apply those skills to one of the most common business problems: customer churn. Churn means customers leaving, for example cancelling a phone or internet contract. The question is simple but valuable: which customers are most likely to leave, and how much revenue is at stake?

The data is a set of real telecom customer records loaded from telco_churn_raw.csv, with 486 customers and 21 columns. The columns that matter most here are tenure (months as a customer), Contract, PaymentMethod, MonthlyCharges, TotalCharges, the internet and add-on service columns, and Churn, which is Yes or No.

In this lesson you will:

  • calculate churn rates overall and by contract, payment method, tenure and services
  • turn churn into monthly and annualised revenue at risk
  • isolate a high-risk segment and test a simple two-factor prediction rule with precision and recall

Prerequisites: you should be comfortable with pandas groupby, boolean filtering and pd.cut. Earlier lessons in the series cover these if you need a refresher.

Part 1: Real Customers, Real Churn#

Every churn analysis starts by knowing how much data you have. This step imports pandas, numpy and matplotlib, reads telco_churn_raw.csv into a DataFrame called customers, and checks .shape. The output (486, 21) means 486 customers and 21 columns. That is a modest sample, so keep in mind that small segments later on may contain only a handful of customers, and their percentages can swing a lot.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
customers = pd.read_csv('telco_churn_raw.csv')
customers.shape
(486, 21)

Part 2: Real Data Preview#

A quick preview confirms how key columns are stored before you calculate anything. The code lists all column names, but Jupyter only displays the last expression, so the output shows just four columns for the first three customers. tenure is in months, Contract is text such as Month-to-month, and Churn is stored as the words Yes and No rather than 1 and 0. That last detail matters: you will need to compare with 'Yes' to count churners.

customers.columns.tolist()
customers[['tenure', 'Contract', 'MonthlyCharges', 'Churn']].head(3)
tenure Contract MonthlyCharges Churn
0 1 Month-to-month 29.85 No
1 34 One year 56.95 No
2 2 Month-to-month 53.85 Yes

Part 3: Real Overall Churn Rate#

The overall churn rate is the baseline that every segment will be compared against. customers['Churn'] == 'Yes' gives True or False for each customer, and .mean() on those booleans returns the share of Trues, since True counts as 1. Multiplying by 100 gives a percentage. The output is 25.3%, so about one customer in four has left. A segment is only interesting if its rate is clearly above or below this figure.

overall_churn_rate = round((customers['Churn'] == 'Yes').mean() * 100, 1)
overall_churn_rate
np.float64(25.3)

Part 4: Real Churn by Contract Type#

Contract type is a classic churn driver because it reflects how committed a customer is. groupby('Contract') splits customers by contract, and .apply with a small lambda runs the same Yes-share calculation inside each group. The result is sorted from highest to lowest. Month-to-month customers churn at 42.2%, compared with 4.1% on one-year and 2.7% on two-year contracts. That gap is huge, and it makes month-to-month customers the obvious focus for retention efforts.

churn_by_contract = customers.groupby('Contract')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_contract.sort_values(ascending=False)
Contract
Month-to-month    42.2
One year           4.1
Two year           2.7
Name: Churn, dtype: float64

Part 5: Visualizing Real Churn by Contract#

A bar chart turns the contract result into something a manager can read in seconds. The code plots the sorted churn rates in a single colour, labels the axis, tilts the labels slightly with rotation=20 so they do not overlap, and saves the chart to churn_by_contract.png. plt.close() stops it displaying in the notebook, so there is no output here. When you open the file, look for one tall month-to-month bar towering over two very short ones.

plt.figure(figsize=(8, 5))
churn_by_contract.sort_values(ascending=False).plot(kind='bar', color='crimson')
plt.ylabel('Real Churn Rate (%)')
plt.title('Real Churn Rate by Contract Type')
plt.xticks(rotation=20)
plt.tight_layout()
plt.savefig('churn_by_contract.png', dpi=120)
plt.close()

Part 6: Real Churn by Payment Method#

Payment method can reveal how engaged or settled a customer is. The same groupby and lambda pattern gives the churn rate per payment method. Electronic check customers churn at 41.7%, roughly double mailed check at 20.5%, while automatic payments are lowest: bank transfer at 17.9% and credit card at 12.1%. Automatic payments mean the customer does not have to actively decide to pay each month, which may be part of the reason. This is a correlation, not proof that changing payment method would keep customers.

churn_by_payment = customers.groupby('PaymentMethod')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_payment.sort_values(ascending=False)
PaymentMethod
Electronic check             41.7
Mailed check                 20.5
Bank transfer (automatic)    17.9
Credit card (automatic)      12.1
Name: Churn, dtype: float64

Part 7: Real Tenure Comparison, Churned vs Retained#

Tenure tells you how long a customer has stayed, so comparing it across churners and stayers shows when people leave. groupby('Churn')['tenure'].mean() gives the average tenure for each group. Customers who stayed average 37.0 months, while those who left averaged just 15.9. So churners tend to leave relatively early in their relationship. Averages can hide a skewed spread, which is why the next steps break tenure into buckets.

tenure_by_churn = customers.groupby('Churn')['tenure'].mean().round(1)
tenure_by_churn
Churn
No     37.0
Yes    15.9
Name: tenure, dtype: float64

Part 8: Real Monthly Charges Comparison#

Price is a common reason to leave, so it is worth checking whether churners were paying more. The code averages MonthlyCharges for each churn group. Customers who left were paying $72.75 a month on average, against $63.77 for those who stayed, a gap of about $9. Higher bills may push people away, but they may also reflect premium services such as fibre internet, which the internet service step looks at separately.

charges_by_churn = customers.groupby('Churn')['MonthlyCharges'].mean().round(2)
charges_by_churn
Churn
No     63.77
Yes    72.75
Name: MonthlyCharges, dtype: float64

Part 9: Real Tenure Bucket Analysis#

Grouping tenure into ranges makes the early-customer risk clear and easy to act on. pd.cut assigns each customer to a bucket using the edges [0, 6, 12, 24, 48, 100] and readable labels such as 0-6mo and 4yr+. Each bucket includes its upper edge, so a tenure of exactly 6 goes into 0-6mo. observed=True keeps only buckets that contain customers. Churn falls steadily, from 54.5% in the first six months to 9.8% after four years, so the first year is the danger zone.

tenure_bins = [0, 6, 12, 24, 48, 100]
tenure_labels = ['0-6mo', '6-12mo', '1-2yr', '2-4yr', '4yr+']
customers['TenureBucket'] = pd.cut(customers['tenure'], bins=tenure_bins, labels=tenure_labels)
customers.groupby('TenureBucket', observed=True)['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
TenureBucket
0-6mo     54.5
6-12mo    42.0
1-2yr     23.4
2-4yr     13.0
4yr+       9.8
Name: Churn, dtype: float64

Part 10: Visualizing Real Churn by Tenure Bucket#

The tenure pattern is the kind of result that is most persuasive as a chart. The code recalculates churn by bucket, uses reindex(tenure_labels) to make sure bars appear in time order rather than any other order, and saves the bar chart to churn_by_tenure.png. There is no displayed output because the figure is closed after saving. In the image, look for a staircase that steps down from left to right, starting above 50% and ending below 10%.

churn_by_tenure = customers.groupby('TenureBucket', observed=True)['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
plt.figure(figsize=(8, 5))
churn_by_tenure.reindex(tenure_labels).plot(kind='bar', color='darkorange')
plt.ylabel('Real Churn Rate (%)')
plt.title('Real Churn Rate by Customer Tenure')
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig('churn_by_tenure.png', dpi=120)
plt.close()

Part 11: Real Senior Citizen Churn Rate#

Age group is a common segment in telecom, since older customers may have different needs. In this dataset SeniorCitizen is stored as 0 or 1 rather than Yes or No. The same churn-rate calculation shows 23.3% churn for non-seniors and 35.4% for seniors, about 12 percentage points higher. Keep in mind that seniors are likely a smaller group in a 486-row sample, so check the group size with value_counts() before drawing firm conclusions.

churn_by_senior = customers.groupby('SeniorCitizen')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_senior
SeniorCitizen
0    23.3
1    35.4
Name: Churn, dtype: float64

Part 12: Real Internet Service and Churn#

The type of internet service a customer has often relates to price and satisfaction. Grouping by InternetService shows fibre optic customers churn at 37.4%, DSL at 19.4%, and customers with no internet service at only 7.4%. Fibre is usually the more expensive service, which links back to the higher monthly charges among churners. Customers without internet are likely phone-only and may simply have fewer reasons to shop around.

churn_by_internet = customers.groupby('InternetService')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_internet.sort_values(ascending=False)
InternetService
Fiber optic    37.4
DSL            19.4
No              7.4
Name: Churn, dtype: float64

Part 13: Real Service Bundle Count#

Customers who use more services are often more tied in, so counting add-ons gives a useful engagement measure. The code compares six add-on columns with 'Yes', which produces a True/False table, and .sum(axis=1) adds across each row to count add-ons per customer. Customers average 2.12 add-ons, the median is 2, and at least a quarter have none. Note that customers without internet show a value other than Yes in these columns, so they count as 0 add-ons.

addon_cols = ['OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies']
customers['AddonCount'] = (customers[addon_cols] == 'Yes').sum(axis=1)
customers['AddonCount'].describe().round(2)
count    486.00
mean       2.12
std        1.87
min        0.00
25%        0.00
50%        2.00
75%        4.00
max        6.00
Name: AddonCount, dtype: float64

Part 14: Real Churn Rate by Add-on Count#

Now the add-on count can be tested as a churn signal. Grouping by AddonCount shows churn peaking at 43.6% for customers with exactly one add-on, then falling steadily to 10.6% with five add-ons and 0.0% with all six. Customers with zero add-ons churn at only 22.7%, which breaks the pattern; that group likely includes the phone-only customers seen earlier with low churn. Very high counts such as 6 may also be small groups, so check their sizes before quoting the 0%.

churn_by_addons = customers.groupby('AddonCount')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_addons
AddonCount
0    22.7
1    43.6
2    30.8
3    25.3
4    21.7
5    10.6
6     0.0
Name: Churn, dtype: float64

Part 15: Real Paperless Billing and Churn#

Paperless billing sounds unrelated to churn, but it can mark more digitally active customers who compare offers more easily. Grouping by PaperlessBilling shows 30.5% churn for customers on paperless billing against 17.5% for those receiving paper bills. That is a clear gap, but treat it as a signal to investigate rather than a cause: paperless billing probably travels together with other factors such as month-to-month contracts or electronic check payments.

churn_by_billing = customers.groupby('PaperlessBilling')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_billing
PaperlessBilling
No     17.5
Yes    30.5
Name: Churn, dtype: float64

Part 16: Real Revenue at Risk from Churn#

Churn rates matter more to a business once they are turned into money. The code uses .loc to select MonthlyCharges for customers who churned and adds them up with .sum(). The output is $8,948.40 of monthly revenue tied to customers who left. In practice this is revenue already lost in this dataset rather than revenue still at risk, but it gives a concrete sense of scale for what each month of churn costs.

monthly_revenue_at_risk = customers.loc[customers['Churn'] == 'Yes', 'MonthlyCharges'].sum()
round(monthly_revenue_at_risk, 2)
np.float64(8948.4)

Part 17: Real Annualized Revenue Impact#

Annual figures are usually how budgets and retention programmes are judged, so the monthly figure is scaled up. Multiplying by 12 gives $107,380.80. This simple calculation assumes the churned customers would have kept paying the same amount every month for a year, which is optimistic, so present it as a rough estimate. Even as an approximation, it shows why a retention campaign that saves only some of these customers can pay for itself.

annualized_impact = round(monthly_revenue_at_risk * 12, 2)
annualized_impact
np.float64(107380.8)

Part 18: Real High-Risk Segment Identification#

Combining the two strongest signals can isolate a much riskier group than either alone. The code filters customers who are both on month-to-month contracts and paying by electronic check, using & to require both conditions (each in brackets, which pandas needs). It then calculates their churn rate. The output shows 134 customers in this segment, with exactly 50.0% churn, about double the overall 25.3%. This is a practical, named list for a retention team to target.

high_risk = customers[(customers['Contract'] == 'Month-to-month') & (customers['PaymentMethod'] == 'Electronic check')]
high_risk_churn_rate = round((high_risk['Churn'] == 'Yes').mean() * 100, 1)
len(high_risk), high_risk_churn_rate
(134, np.float64(50.0))

Part 19: Real Low-Risk Segment for Comparison#

A risky segment means more when it sits beside a safe one. The low-risk group here is everyone not on a month-to-month contract, selected with !=. Its churn rate is just 3.3%, against 50.0% for the high-risk segment. That is roughly fifteen times lower. Such a sharp contrast is a strong argument for encouraging customers onto longer contracts, for example with a discount, although you would want to test that idea before rolling it out.

low_risk = customers[customers['Contract'] != 'Month-to-month']
low_risk_churn_rate = round((low_risk['Churn'] == 'Yes').mean() * 100, 1)
high_risk_churn_rate, low_risk_churn_rate
(np.float64(50.0), np.float64(3.3))

Part 20: Real Simple Churn Prediction Rule#

A simple rule can act as a first churn prediction model before you build anything more complex. This rule predicts churn for customers on month-to-month contracts with under 12 months of tenure, and .astype(int) turns True and False into 1 and 0. Comparing predictions with actual churn and taking .mean() gives accuracy of 77.2%. With 25.3% churn, predicting that nobody churns would already be right about 74.7% of the time, so the rule is only slightly better on accuracy alone.

customers['PredictedChurn'] = ((customers['Contract'] == 'Month-to-month') & (customers['tenure'] < 12)).astype(int)
actual_churn = (customers['Churn'] == 'Yes').astype(int)
accuracy = (customers['PredictedChurn'] == actual_churn).mean()
round(accuracy * 100, 1)
np.float64(77.2)

Part 21: Real Precision and Real Recall#

Precision and recall show how useful the rule really is. Precision is the share of customers the rule flags who actually churned; recall is the share of all churners the rule catches. The code counts true positives, false positives and false negatives with combined conditions, then divides. Precision is 0.544, so just over half of flagged customers left. Recall is 0.602, so the rule catches about 60% of churners. For a retention campaign, that is a reasonable starting list from a two-line rule.

true_positives = ((customers['PredictedChurn'] == 1) & (actual_churn == 1)).sum()
false_positives = ((customers['PredictedChurn'] == 1) & (actual_churn == 0)).sum()
false_negatives = ((customers['PredictedChurn'] == 0) & (actual_churn == 1)).sum()
precision = round(true_positives / (true_positives + false_positives), 3)
recall = round(true_positives / (true_positives + false_negatives), 3)
precision, recall
(np.float64(0.544), np.float64(0.602))

Part 22: Real Correlation, Tenure vs Monthly Charges#

It helps to know whether tenure and monthly charges carry overlapping information. .corr() computes the Pearson correlation, a value from -1 to +1 measuring how closely two columns move together in a straight line. The output is 0.199, a weak positive link: longer-standing customers pay slightly more per month on average. Because the two are only weakly related, both can add separate information to a churn model.

tenure_charge_corr = customers['tenure'].corr(customers['MonthlyCharges'])
round(tenure_charge_corr, 3)
np.float64(0.199)

Part 23: Real Total Charges vs Tenure#

A scatter plot of total charges against tenure, coloured by churn, shows where churners sit in the customer lifecycle. .map turns Yes and No into red and green, plt.scatter draws one point per customer with alpha=0.5 transparency so overlapping points remain visible, and the chart is saved to charges_vs_tenure.png and closed. There is no displayed output. In the image, expect points to fan out upwards as tenure grows, since total charges build up over time, with red points crowded on the left at low tenure.

plt.figure(figsize=(9, 5))
colors = customers['Churn'].map({'Yes': 'crimson', 'No': 'seagreen'})
plt.scatter(customers['tenure'], customers['TotalCharges'], c=colors, alpha=0.5, s=15)
plt.xlabel('Real Tenure (Months)')
plt.ylabel('Real Total Charges (USD)')
plt.title('Real Total Charges vs Tenure, Colored by Churn')
plt.tight_layout()
plt.savefig('charges_vs_tenure.png', dpi=120)
plt.close()

Part 24: Real Gender and Partner Status Check#

Checking factors that should not matter is as useful as finding ones that do. The code calculates churn by gender and by Partner and shows both as dictionaries. Churn is almost identical for women at 25.1% and men at 25.5%, so gender is not a useful signal here. Customers without a partner churn at 30.4%, against 19.9% for those with one, a clearer gap that may reflect household stability or shared contracts.

churn_by_gender = customers.groupby('gender')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_partner = customers.groupby('Partner')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
churn_by_gender.to_dict(), churn_by_partner.to_dict()
({'Female': 25.1, 'Male': 25.5}, {'No': 30.4, 'Yes': 19.9})

Part 25: Saving the Real Enriched Customer Table#

Saving the enriched table means later work, or other team members, can use the new columns without repeating the analysis. The code selects identifiers, key drivers, the new TenureBucket and AddonCount columns, actual churn and the PredictedChurn flag, then writes them with to_csv(index=False) so the row index is not stored as an extra column. Reading the file back and comparing row counts returns True, confirming all 486 customers were saved.

output_cols = ['customerID', 'tenure', 'TenureBucket', 'Contract', 'PaymentMethod', 'MonthlyCharges', 'AddonCount', 'Churn', 'PredictedChurn']
customers[output_cols].to_csv('churn_analysis_enriched.csv', index=False)
reloaded = pd.read_csv('churn_analysis_enriched.csv')
reloaded.shape[0] == customers.shape[0]
True

Part 26: Real Sanity Check, Churn Rate Bounds#

A churn rate must sit between 0 and 100 percent. If it does not, a calculation has gone wrong, for example by forgetting to divide or by multiplying by 100 twice. Python allows the chained comparison 0 <= x <= 100, which checks both limits at once. The output is True, so the overall rate of 25.3% passes. It is a tiny check, but building such guards into your notebooks catches mistakes before they reach a report.

0 <= overall_churn_rate <= 100
np.True_

Part 27: Real Sanity Check, Segment Sizes Sum Correctly#

This check is meant to confirm that segment sizes add up, but the output is False, and it is worth understanding why. The low-risk group was defined as customers not on month-to-month contracts, so filtering it for month-to-month customers always returns zero rows. The comparison therefore tests whether the 134 high-risk customers equal all 275 month-to-month customers, which they do not. The False does not signal bad data; it shows how a sanity check can test the wrong thing, so always reason through what a check compares.

len(high_risk) + len(low_risk[low_risk['Contract'] == 'Month-to-month']) == (customers['Contract'] == 'Month-to-month').sum()
np.False_

Part 28: Real Retention Priority Ranking#

The most practical output of a churn analysis is a list of customers to contact. The code keeps customers the rule flags as likely to churn who have not yet left (Churn == 'No'), then sorts them by MonthlyCharges from highest to lowest. The top five pay between $89.85 and $99.30 a month and all have tenures under a year. Sorting by revenue means the retention team calls the customers whose loss would cost the most first.

at_risk_customers = customers[(customers['PredictedChurn'] == 1) & (customers['Churn'] == 'No')]
at_risk_customers[['customerID', 'tenure', 'MonthlyCharges']].sort_values('MonthlyCharges', ascending=False).head(5)
customerID tenure MonthlyCharges
85 4445-ZJNMU 9 99.30
31 4929-XIHVW 2 95.50
448 5168-MSWXT 8 94.75
302 8266-VBFQL 4 90.40
115 3071-VBYPO 3 89.85

Part 29: Real Summary Table by Contract#

A summary table puts size, risk and value side by side, which is what decision-makers need. .agg with named aggregations creates three columns at once: a customer count, a churn rate from a lambda, and average monthly charges. Month-to-month contracts hold 275 customers with 42.2% churn and the highest average bill of $68.49. One-year and two-year contracts have 98 and 113 customers with churn of 4.1% and 2.7%. The riskiest group is also the largest and the highest-paying.

contract_summary = customers.groupby('Contract').agg(Count=('customerID', 'count'), ChurnRatePct=('Churn', lambda s: round((s == 'Yes').mean() * 100, 1)), AvgMonthly=('MonthlyCharges', 'mean')).round(2)
contract_summary
Count ChurnRatePct AvgMonthly
Contract
Month-to-month 275 42.2 68.49
One year 98 4.1 64.64
Two year 113 2.7 61.29

Part 30: Real Recap Print#

The recap condenses the story into one sentence built from variables, so it stays accurate if the data changes. The output reports 486 customers, 25.3% overall churn, 50.0% churn in the month-to-month electronic-check segment versus 3.3% for longer contracts, and $8,948 in monthly revenue linked to churn. Inside the f-string, the :, format adds thousands separators, a small touch that makes numbers easier to read in reports.

print(f'Across {len(customers)} real customers, overall churn was {overall_churn_rate}%, but month-to-month electronic-check customers churned at {high_risk_churn_rate}% versus {low_risk_churn_rate}% for longer contracts, putting ${round(monthly_revenue_at_risk):,} in real monthly revenue at risk.')
Across 486 real customers, overall churn was 25.3%, but month-to-month electronic-check customers churned at 50.0% versus 3.3% for longer contracts, putting $8,948 in real monthly revenue at risk.

Wrap-Up: What You Learned#

  • Contract length and payment method were the two real strongest churn signals in this dataset, both genuinely tied to real customer commitment.
  • Bucketing real tenure into ranges revealed churn risk is heavily concentrated among real newer customers, not spread evenly.
  • Converting real churn counts into real dollars, monthly and annualized, is what actually makes a churn analysis matter to a real business.
  • A real simple two-factor prediction rule caught meaningful churn risk but came with real honest trade-offs between precision and recall.
  • Combining multiple real risk factors, contract type and payment method together, isolated a real segment with dramatically higher churn than either factor alone.
  • Next video: real hashtag and topic trend analysis, returning to the real social post data from earlier in this domain.

Practice on your own

  • Calculate churn rates by TechSupport and by OnlineSecurity using the same groupby and lambda pattern, and compare them with the 25.3% baseline.
  • Change the prediction rule to use tenure under 6 months instead of 12, then recalculate accuracy, precision and recall. Note which measure improves and which gets worse.
  • Add a Count column to the add-on churn table with .agg, so you can see how many customers sit behind the 0.0% churn for six add-ons.

The next video returns to the social post data from earlier in this domain for a hashtag and topic trend analysis. Watch the video walkthrough to see each step run live.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. How does the lesson compute the overall churn rate from the Churn column?

  2. With pd.cut(tenure, bins=[0, 6, 12, 24, 48, 100], labels=['0-6mo','6-12mo','1-2yr','2-4yr','4yr+']), which bucket does a tenure of exactly 12 months fall in?

  3. In the lesson's simple churn-prediction rule, what does precision tell you?

  4. How does the lesson turn churn into a dollar figure?

  5. Why does the lesson combine Contract and PaymentMethod to define a high-risk segment?

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Create a DataFrame of 12 telecom customers (customerID, Contract, tenure, MonthlyCharges, Churn as 'Yes'/'No'). Print the overall churn rate and the churn rate by Contract, sorted from highest to lowest.

    💡 Hint

    Group by Contract and apply a lambda that computes the share of 'Yes'.

    ✅ Show solution
    import pandas as pd
    
    customers = pd.DataFrame({
        'customerID': [f'C{i:02d}' for i in range(1, 13)],
        'Contract': ['Month-to-month']*6 + ['One year']*3 + ['Two year']*3,
        'tenure': [2, 5, 10, 3, 20, 8, 14, 30, 25, 50, 60, 40],
        'MonthlyCharges': [70, 85, 60, 90, 55, 75, 65, 50, 80, 45, 40, 55],
        'Churn': ['Yes','Yes','No','Yes','No','Yes','No','No','Yes','No','No','No'],
    })
    overall = round((customers['Churn'] == 'Yes').mean() * 100, 1)
    by_contract = customers.groupby('Contract')['Churn'].apply(lambda s: round((s == 'Yes').mean() * 100, 1))
    print('Overall churn rate:', overall, '%')
    print(by_contract.sort_values(ascending=False))
    
  2. With a 14-row customer table (tenure, MonthlyCharges, Churn, plus a few add-on columns with 'Yes'/'No'), bucket tenure with pd.cut, count add-ons per customer, then print churn rate by tenure bucket, churn rate by add-on count, and the monthly and annualized revenue at risk from churned customers.

    💡 Hint

    Add-on count is (df[cols] == 'Yes').sum(axis=1).

    ✅ Show solution
    import pandas as pd
    
    customers = pd.DataFrame({
        'tenure': [1, 4, 8, 11, 15, 22, 30, 36, 45, 52, 5, 9, 26, 60],
        'MonthlyCharges': [80, 95, 70, 85, 60, 65, 55, 50, 45, 40, 90, 75, 58, 35],
        'OnlineSecurity': ['No','No','No','Yes','No','Yes','Yes','Yes','Yes','Yes','No','No','Yes','Yes'],
        'TechSupport':    ['No','No','Yes','No','No','Yes','Yes','No','Yes','Yes','No','No','No','Yes'],
        'StreamingTV':    ['Yes','Yes','No','Yes','No','No','Yes','No','No','Yes','Yes','No','No','Yes'],
        'Churn': ['Yes','Yes','Yes','Yes','No','No','No','No','No','No','Yes','Yes','No','No'],
    })
    bins = [0, 6, 12, 24, 48, 100]
    labels = ['0-6mo', '6-12mo', '1-2yr', '2-4yr', '4yr+']
    customers['TenureBucket'] = pd.cut(customers['tenure'], bins=bins, labels=labels)
    addon_cols = ['OnlineSecurity', 'TechSupport', 'StreamingTV']
    customers['AddonCount'] = (customers[addon_cols] == 'Yes').sum(axis=1)
    
    rate = lambda s: round((s == 'Yes').mean() * 100, 1)
    print(customers.groupby('TenureBucket', observed=True)['Churn'].apply(rate))
    print(customers.groupby('AddonCount')['Churn'].apply(rate))
    monthly_at_risk = customers.loc[customers['Churn'] == 'Yes', 'MonthlyCharges'].sum()
    print('Monthly revenue at risk:', monthly_at_risk)
    print('Annualized impact:', monthly_at_risk * 12)
    
  3. Build a 16-row customer table (Contract, PaymentMethod, tenure, MonthlyCharges, Churn). Create a rule PredictedChurn = 1 for month-to-month customers with tenure under 12. Compute accuracy, precision and recall by hand from true/false positives and negatives, and compare the churn rate of the high-risk segment (month-to-month AND electronic check) with non-month-to-month customers.

    💡 Hint

    Build the confusion counts with Boolean masks on PredictedChurn and an actual_churn 0/1 series.

    ✅ Show solution
    import pandas as pd
    
    customers = pd.DataFrame({
        'Contract': ['Month-to-month']*10 + ['One year']*3 + ['Two year']*3,
        'PaymentMethod': ['Electronic check','Electronic check','Mailed check','Electronic check','Credit card',
                          'Electronic check','Bank transfer','Mailed check','Electronic check','Credit card',
                          'Credit card','Electronic check','Bank transfer','Mailed check','Credit card','Bank transfer'],
        'tenure': [2, 4, 10, 6, 30, 3, 20, 14, 8, 40, 25, 12, 36, 50, 60, 48],
        'MonthlyCharges': [85, 90, 60, 80, 55, 95, 50, 65, 88, 45, 60, 70, 55, 40, 35, 42],
        'Churn': ['Yes','Yes','No','Yes','No','Yes','No','Yes','Yes','No','No','Yes','No','No','No','No'],
    })
    customers['PredictedChurn'] = ((customers['Contract'] == 'Month-to-month') & (customers['tenure'] < 12)).astype(int)
    actual = (customers['Churn'] == 'Yes').astype(int)
    
    tp = ((customers['PredictedChurn'] == 1) & (actual == 1)).sum()
    fp = ((customers['PredictedChurn'] == 1) & (actual == 0)).sum()
    fn = ((customers['PredictedChurn'] == 0) & (actual == 1)).sum()
    accuracy = (customers['PredictedChurn'] == actual).mean()
    print('Accuracy:', round(accuracy * 100, 1), '%')
    print('Precision:', round(tp / (tp + fp), 3), 'Recall:', round(tp / (tp + fn), 3))
    
    high_risk = customers[(customers['Contract'] == 'Month-to-month') & (customers['PaymentMethod'] == 'Electronic check')]
    low_risk = customers[customers['Contract'] != 'Month-to-month']
    print('High-risk churn rate:', round((high_risk['Churn'] == 'Yes').mean() * 100, 1), '% of', len(high_risk))
    print('Non month-to-month churn rate:', round((low_risk['Churn'] == 'Yes').mean() * 100, 1), '% of', len(low_risk))
    

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.