Editor

Engineer New Features

Advanced · Write the code · from Predict Customer Churn: End-to-End Data Analysis (with sklearn)

From the lesson: Step 3: Feature Engineering

Raw data rarely gives the best predictions. Feature engineering is the art of creating new columns that capture patterns more clearly. For example, instead of raw tenure in months, we can create buckets like "new" (0–6 months), "growing" (7–24), and "loyal" (25+). This helps the model spot thresholds.

Read this part of the lesson

Starting from the provided DataFrame df, create two new columns:

1. tenure_bucket - 'new' if tenure_months <= 6, 'growing' if 7–24, 'loyal' if 25+. Use pd.cut() or conditional logic.

2. charge_per_month - total_charges / tenure_months (handle division by zero by replacing inf/NaN with monthly_charges).

Print the value counts of tenure_bucket, then print the first 5 rows showing customer_id, tenure_bucket, and charge_per_month.

import pandas as pd
import numpy as np
data = {
'customer_id': list(range(1, 21)),
'tenure_months': [2, 34, 5, 45, 12, 1, 60, 8, 24, 48,
3, 36, 7, 52, 15, 2, 42, 10, 30, 6],
'monthly_charges': [70, 45, 85, 30, 65, 90, 25, 75, 55, 35,
88, 40, 78, 28, 60, 92, 32, 72, 50, 82],
'total_charges': [140, 1530, 425, 1350, 780, 90, 1500, 600, 1320, 1680,
264, 1440, 546, 1456, 900, 184, 1344, 720, 1500, 492],
'contract': ['Month', 'Year', 'Month', 'TwoYear', 'Month', 'Month', 'TwoYear',
'Month', 'Year', 'TwoYear', 'Month', 'Year', 'Month', 'TwoYear',
'Year', 'Month', 'TwoYear', 'Month', 'Year', 'Month'],
'churned': [1, 0, 1, 0, 1, 1, 0, 1, 0, 0,
1, 0, 1, 0, 0, 1, 0, 1, 0, 1]
}
df = pd.DataFrame(data)
# Create tenure_bucket and charge_per_month columns

More Churn Prediction exercises

All Python exercises · 50 practice problems · Practical Projects quiz