How to Build a Customer Churn Prediction Model Using Python
Dec 04, 2026 4 Min Read 81 Views
(Last Updated)
Losing existing customers can be more expensive than retaining them. But how can businesses identify customers who are likely to leave before they actually cancel their subscriptions? Customer behaviour, purchase history, service usage, and complaints often contain patterns that indicate potential churn. Machine learning helps analyze these patterns and estimate the likelihood of customers leaving.
Building a customer churn prediction model using Python allows businesses to identify at-risk customers and develop targeted retention strategies. This tutorial explains the complete process, from preparing customer data to training, evaluating, and using a machine learning model.
Table of contents
- Quick Answer
- What Is Customer Churn Prediction?
- Important Features Used in Churn Prediction
- Which Python Libraries Are Required?
- How to Build a Customer Churn Prediction Model Using Python Step by Step
- Step 1. Install the Required Libraries
- Step 2. Load and Explore the Dataset
- Step 3. Clean and Prepare Customer Data
- Step 4. Split the Data into Training and Testing Sets
- Step 5. Build and Train the Classification Model
- Step 6. Evaluate Model Performance
- Step 7. Predict Customer Churn
- How to Interpret Customer Churn Model Results
- Conclusion
- FAQs
- Which algorithm is best for customer churn prediction?
- Can beginners build a churn prediction model?
- Which dataset is suitable for churn prediction?
- How can businesses use churn predictions?
- What is a good accuracy for a churn prediction model?
- Is customer churn prediction supervised learning?
Quick Answer
| A customer churn prediction model using Python is a machine learning system that predicts whether a customer is likely to stop using a company’s services. It uses historical customer data, such as tenure, monthly charges, contract type, and service usage. Developers can build the model using Pandas for data preparation and Scikit-learn for classification, training, and evaluation. |
What Is Customer Churn Prediction?
Customer churn prediction uses historical data to estimate the probability that an existing customer will discontinue a product or service.
It is a binary classification problem because the model generally predicts one of two outcomes: churn or no churn. However, it can also generate a probability score that helps businesses prioritize retention efforts.
For example, a telecommunications company might identify customers with short contracts, high monthly bills, and repeated service complaints as potentially at risk. The model learns relationships between customer characteristics and previous churn outcomes rather than relying entirely on predefined rules.
Customer churn prediction helps Business Analysts identify at-risk customers and develop effective retention strategies. Strengthen your skills in customer data analysis, predictive analytics, and business problem-solving with HCL GUVI’s Business Analyst Course. Learn to translate customer behaviour patterns into actionable business insights.
Important Features Used in Churn Prediction
Selecting relevant customer attributes is essential when building a customer churn prediction model using Python. These features help identify patterns in customer behaviour, billing history, and service usage.
| Feature | Description |
|---|---|
| Tenure | Duration of the customer relationship |
| Monthly Charges | Amount billed each month |
| Contract Type | Monthly, yearly, or longer-term agreement |
| Payment Method | Method used for bill payments |
| Internet Service | Type of subscribed internet service |
| Support History | Previous complaints or service requests |
| Churn | Target variable indicating whether a customer left |
- According to Bain & Company, a 5% increase in customer retention can increase profits by 25% to 95%, depending on the industry and business model.
- The IBM Telco Customer Churn dataset contains 7,043 customer records, with approximately 26.5% classified as churned customers. This makes it a useful dataset for practicing machine learning classification.
- A model with 80% accuracy can still miss most customers who leave. Class imbalance can make accuracy misleading, which is why recall, precision, and F1-score are important when evaluating churn prediction models.
Which Python Libraries Are Required?
Python provides several libraries for preparing customer records and developing predictive models. Each library supports a different stage of building a customer churn prediction model using Python, from cleaning data to evaluating predictions.
| Library | Purpose |
|---|---|
| Pandas | Loading, cleaning, and analyzing customer data |
| NumPy | Numerical computations |
| Scikit-learn | Preprocessing, model training, and evaluation |
| Matplotlib | Visualizing customer trends and results |
This tutorial uses Logistic Regression because it provides an interpretable baseline for binary classification. More advanced approaches, including Random Forest and Gradient Boosting, can be evaluated after establishing initial performance.
How to Build a Customer Churn Prediction Model Using Python Step by Step
The following implementation uses the IBM Telco Customer Churn dataset. It contains customer demographics, service subscriptions, billing information, and churn labels.
Step 1. Install the Required Libraries
Install the necessary packages using your terminal or a Google Colab notebook. These libraries support data processing, predictive modeling, and model evaluation.
pip install pandas numpy scikit-learn matplotlib
Once installation is complete, import the required modules into your Python environment.
Step 2. Load and Explore the Dataset
Download the IBM Telco Customer Churn dataset and save the CSV file as WA_Fn-UseC_-Telco-Customer-Churn.csv.
import pandas as pd
df = pd.read_csv(
"WA_Fn-UseC_-Telco-Customer-Churn.csv"
)
print(df.head())
print(df.info())
print(df["Churn"].value_counts())
The head() function displays sample customer records, while info() identifies column types and missing values. Checking the target distribution also reveals whether churned and retained customers are balanced.
Step 3. Clean and Prepare Customer Data
Effective data preprocessing improves the reliability of machine learning models. The Telco dataset contains numerical and categorical features that require different transformations. Preparing these features correctly is essential for training a customer churn prediction model using Python.
First, convert the TotalCharges column into numerical values and remove the customer identifier.
df["TotalCharges"] = pd.to_numeric(
df["TotalCharges"], errors="coerce"
)
df = df.drop(columns=["customerID"])
df["Churn"] = df["Churn"].map({
"Yes": 1,
"No": 0
})
Missing numerical values will be handled during preprocessing. The target variable now uses 1 for churn and 0 for retained customers.
Step 4. Split the Data into Training and Testing Sets
A machine learning model needs separate datasets for learning and evaluation. An 80:20 split is a common starting point for a beginner classification project.
from sklearn.model_selection import train_test_split
X = df.drop(columns=["Churn"])
y = df["Churn"]
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.2,
random_state=42,
stratify=y
)
The stratify parameter helps preserve the churn distribution across both datasets. For time-dependent predictions, a chronological split may be more appropriate to prevent future information from influencing earlier predictions.
Step 5. Build and Train the Classification Model
The next step is creating preprocessing pipelines for numerical and categorical variables. Scikit-learn’s Pipeline documentation explains how combining preprocessing with model training reduces data leakage risks.
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
numeric_cols = X.select_dtypes(
include="number"
).columns.tolist()
categorical_cols = X.select_dtypes(
exclude="number"
).columns.tolist()
numeric_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_pipeline = Pipeline([
("imputer", SimpleImputer(
strategy="most_frequent"
)),
("encoder", OneHotEncoder(
handle_unknown="ignore"
))
])
preprocessor = ColumnTransformer([
("numeric", numeric_pipeline, numeric_cols),
("categorical", categorical_pipeline, categorical_cols)
])
model = Pipeline([
("preprocessor", preprocessor),
("classifier", LogisticRegression(
max_iter=1000
))
])
model.fit(X_train, y_train)
This pipeline handles missing values, scales numerical columns, and encodes categorical information. Logistic Regression then learns relationships between customer characteristics and churn outcomes.
Step 6. Evaluate Model Performance
Accuracy alone may be misleading when churned customers represent a smaller portion of the dataset. Precision, recall, F1-score, and ROC-AUC provide additional information about classification performance.
from sklearn.metrics import (
classification_report,
confusion_matrix,
roc_auc_score
)
y_pred = model.predict(X_test)
y_prob = model.predict_proba(X_test)[:, 1]
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))
print("ROC-AUC:", roc_auc_score(y_test, y_prob))
The classification report shows precision, recall, and F1-score for each class. In churn prediction, recall for churned customers is particularly important when missing at-risk customers carries substantial business costs.
Step 7. Predict Customer Churn
After evaluation, the model can estimate churn probabilities for new customers. The example below uses an existing test record to demonstrate the prediction process.
new_customer = X_test.iloc[[0]]
churn_probability = model.predict_proba(
new_customer
)[0, 1]
print(
f"Churn probability: {churn_probability:.2%}"
)
The output represents the model’s estimated churn probability, not a guaranteed outcome. Businesses can use validated risk thresholds to prioritize appropriate retention campaigns.
How to Interpret Customer Churn Model Results
Evaluating a customer churn prediction model using Python requires examining multiple performance metrics rather than relying on accuracy alone. Each metric provides different insights into how effectively the model identifies customers who may leave.
| Metric | Business Interpretation |
|---|---|
| Accuracy | Percentage of overall correct predictions |
| Precision | Proportion of predicted churners who actually churned |
| Recall | Proportion of actual churners correctly identified |
| F1-Score | Balance between precision and recall |
| ROC-AUC | Ability to distinguish churned and retained customers across thresholds |
A model with high accuracy may still miss many customers who actually leave. Business Analysts should therefore evaluate the cost of missed churn cases against unnecessary retention offers.
Building a customer churn prediction model is only the first step towards improving customer retention. Develop your expertise in interpreting analytical results, evaluating business performance, and recommending data-backed retention strategies with HCL GUVI’s Business Analyst Course.
Conclusion
Building a customer churn prediction model using Python provides practical experience in data preprocessing, classification, and model evaluation.
Pandas and Scikit-learn make it possible to convert historical customer records into predictive insights. However, successful churn prediction requires more than training an accurate model.
Reliable data, appropriate evaluation metrics, and carefully designed retention strategies help businesses turn predictions into measurable customer retention improvements.
FAQs
Which algorithm is best for customer churn prediction?
Logistic Regression is a useful baseline because it is interpretable and relatively simple. Random Forest and Gradient Boosting may provide better performance depending on the dataset.
Can beginners build a churn prediction model?
Yes. Basic knowledge of Python, Pandas, and machine learning classification is sufficient to begin. Small projects help learners understand preprocessing, training, and evaluation.
Which dataset is suitable for churn prediction?
The IBM Telco Customer Churn dataset is widely used for beginner projects. It includes customer tenure, subscription details, billing information, and churn labels.
How can businesses use churn predictions?
Businesses can identify at-risk customers, prioritize support, and test targeted retention campaigns. Predictions should be combined with customer context and measurable retention outcomes.
What is a good accuracy for a churn prediction model?
There is no universal accuracy target. Performance depends on class distribution, business costs, and how accurately the model identifies customers who are likely to churn.
Is customer churn prediction supervised learning?
Yes. It is typically a supervised classification task because the model learns from historical customer records with known churn outcomes.



Did you enjoy this article?