Editor

Encode and Scale Features

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

From the lesson: Step 4: Prepare Features for the Model

Machine learning models work with numbers, not strings. We need to convert categorical columns like "contract" into numerical form. One-hot encoding creates a separate binary column for each category. We also need to separate our features (X) from our target (y).

Read this part of the lesson

Starting from the provided DataFrame df:

1. One-hot encode the contract column using pd.get_dummies() with drop_first=True.

2. Create feature matrix X with columns: tenure_months, monthly_charges, and the encoded contract columns. Create target y from the churned column.

3. Scale X using StandardScaler from sklearn.

4. Print the shape of X and the column names.

import pandas as pd
from sklearn.preprocessing import StandardScaler
data = {
'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],
'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)
# One-hot encode, create X and y, scale features

More Churn Prediction exercises

All Python exercises · 50 practice problems · Practical Projects quiz