First 5 rows of the dataset:
CustomerID Count Country State City Zip Code Lat Long
0 3668-QPYBK 1 United States California Los Angeles 90003 33.964131, -118.272783
1 9237-HQITU 1 United States California Los Angeles 90005 34.059281, -118.30742
2 9305-CDSKC 1 United States California Los Angeles 90006 34.048013, -118.293953
3 7892-POOKP 1 United States California Los Angeles 90010 34.062125, -118.315709
4 0280-XJGEX 1 United States California Los Angeles 90015 34.039224, -118.266293
Latitude Longitude Gender Senior Citizen Partner Dependents Tenure Months Phone Service
0 33.96 -118.27 Male No No No 2 Yes
1 34.06 -118.31 Female No No Yes 2 Yes
2 34.05 -118.29 Female No No Yes 8 Yes
3 34.06 -118.32 Female No Yes Yes 28 Yes
4 34.04 -118.27 Male No No Yes 49 Yes
Multiple Lines Internet Service Online Security Online Backup Device Protection Tech Support
0 No DSL Yes Yes No No
1 No Fiber optic No No No No
2 Yes Fiber optic No No Yes No
3 Yes Fiber optic No No Yes Yes
4 Yes Fiber optic No Yes Yes No
Streaming TV Streaming Movies Contract Paperless Billing Payment Method
0 No No Month-to-month Yes Mailed check
1 No No Month-to-month Yes Electronic check
2 Yes Yes Month-to-month Yes Electronic check
3 Yes Yes Month-to-month Yes Electronic check
4 Yes Yes Month-to-month Yes Bank transfer (automatic)
Summary Statistics:
CustomerID Count Country State City Zip Code
count 7043 7043.00 7043 7043 7043 7043.00
unique 7043 NaN 1 1 1129 NaN
top 3668-QPYBK NaN United States California Los Angeles NaN
freq 1 NaN 7043 7043 305 NaN
mean NaN 1.00 NaN NaN NaN 93521.96
std NaN 0.00 NaN NaN NaN 1865.79
min NaN 1.00 NaN NaN NaN 90001.00
25% NaN 1.00 NaN NaN NaN 92102.00
50% NaN 1.00 NaN NaN NaN 93552.00
75% NaN 1.00 NaN NaN NaN 95351.00
max NaN 1.00 NaN NaN NaN 96161.00
code
Lat Long Latitude Longitude Gender Senior Citizen Partner Dependents \
count 7043 7043.00 7043.00 7043 7043 7043 7043
unique 1652 NaN NaN 2 2 2 2
top 33.964131, -118.272783 NaN NaN Male No No No
freq 5 NaN NaN 3555 5901 3641 5416
mean NaN 36.28 -119.80 NaN NaN NaN NaN
std NaN 2.46 2.16 NaN NaN NaN NaN
min NaN 32.56 -124.30 NaN NaN NaN NaN
25% NaN 34.03 -121.82 NaN NaN NaN NaN
50% NaN 36.39 -119.73 NaN NaN NaN NaN
75% NaN 38.22 -118.04 NaN NaN NaN NaN
max NaN 41.96 -114.19 NaN NaN NaN NaN
code
Tenure Months Phone Service Multiple Lines Internet Service Online Security Online Backup \
count 7043.00 7043 7043 7043 7043 7043
unique NaN 2 3 3 3 3
top NaN Yes No Fiber optic No No
freq NaN 6361 3390 3096 3498 3088
mean 32.37 NaN NaN NaN NaN NaN
std 24.56 NaN NaN NaN NaN NaN
min 0.00 NaN NaN NaN NaN NaN
25% 9.00 NaN NaN NaN NaN NaN
50% 29.00 NaN NaN NaN NaN NaN
75% 55.00 NaN NaN NaN NaN NaN
max 72.00 NaN NaN NaN NaN NaN
code
Device Protection Tech Support Streaming TV Streaming Movies Contract \
count 7043 7043 7043 7043 7043
unique 3 3 3 3 3
top No No No No Month-to-month
freq 3095 3473 2810 2785 3875
mean NaN NaN NaN NaN NaN
std NaN NaN NaN NaN NaN
min NaN NaN NaN NaN NaN
25% NaN NaN NaN NaN NaN
50% NaN NaN NaN NaN NaN
75% NaN NaN NaN NaN NaN
max NaN NaN NaN NaN NaN
count 7043 7043 7043.00 7043 7043
unique 2 4 NaN 6531 2
top Yes Electronic check NaN 20.2 No
freq 4171 2365 NaN 11 5174
mean NaN NaN 64.76 NaN NaN
std NaN NaN 30.09 NaN NaN
min NaN NaN 18.25 NaN NaN
25% NaN NaN 35.50 NaN NaN
50% NaN NaN 70.35 NaN NaN
75% NaN NaN 89.85 NaN NaN
max NaN NaN 118.75 NaN NaN
code
Churn Value Churn Score CLTV Churn Reason
count 7043.00 7043.00 7043.00 1869
unique NaN NaN NaN 20
top NaN NaN NaN Attitude of support person
freq NaN NaN NaN 192
mean 0.27 58.70 4400.30 NaN
std 0.44 21.53 1183.06 NaN
min 0.00 5.00 2003.00 NaN
25% 0.00 40.00 3469.00 NaN
50% 0.00 61.00 4527.00 NaN
75% 1.00 75.00 5380.50 NaN
max 1.00 100.00 6500.00 NaN
Missing Values:
CustomerID 0
Count 0
Country 0
State 0
City 0
Zip Code 0
Lat Long 0
Latitude 0
Longitude 0
Gender 0
Senior Citizen 0
Partner 0
Dependents 0
Tenure Months 0
Phone Service 0
Multiple Lines 0
Internet Service 0
Online Security 0
Online Backup 0
Device Protection 0
Tech Support 0
Streaming TV 0
Streaming Movies 0
Contract 0
Paperless Billing 0
Payment Method 0
Monthly Charges 0
Total Charges 0
Churn Label 0
Churn Value 0
Churn Score 0
CLTV 0
Churn Reason 5174
dtype: int64
For a dataset like above, do Customer Lifetime Value (CLTV) Optimization in python:
Analyze factors affecting CLTV and model its correlation with churn and other behaviors.
Suggest optimization strategies.
To perform Customer Lifetime Value (CLTV) Optimization using the provided dataset, we will follow a structured approach:
Data Loading and Preprocessing
Exploratory Data Analysis (EDA)
Correlation Analysis
Modeling CLTV and Churn
Optimization Strategies
Below, each step is detailed with corresponding Python code snippets using libraries such as Pandas, NumPy, Matplotlib, Seaborn, and Scikit-learn.
1. Data Loading and Preprocessing
a. Import Necessary Libraries
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.metrics import mean_squared_error, r2_score, classification_report, confusion_matrix, roc_auc_score
b. Load the Data
Assuming the data is in a CSV file named customer_data.csv:
python
# Load the dataset
df = pd.read_csv('customer_data.csv')
# Display the first few rows
print(df.head())
c. Handle Missing Values
From the dataset information, only Churn Reason has missing values.
python
# Check missing values
print(df.isnull().sum())
# Handle missing values in 'Churn Reason'
# Assuming missing 'Churn Reason' implies no churn, or can be labeled as 'Not Churned'
df['Churn Reason'] = df['Churn Reason'].fillna('Not Churned')
d. Data Type Conversion
Convert relevant columns to appropriate data types.
python
# Convert 'Total Charges' to numeric, handling any non-numeric values
df['Total Charges'] = pd.to_numeric(df['Total Charges'], errors='coerce')
# After conversion, check for any NaNs introduced
print(df['Total Charges'].isnull().sum())
# Fill or drop NaNs in 'Total Charges'
df['Total Charges'] = df['Total Charges'].fillna(df['Monthly Charges'] * df['Tenure Months'])
# Verify no missing values remain
print(df.isnull().sum())
e. Feature Engineering
Extract Latitude and Longitude:
python
# Split 'Lat Long' into 'Latitude' and 'Longitude' if necessary
df[['Latitude', 'Longitude']] = df['Lat Long'].str.split(',', expand=True).astype(float)
# Drop 'Lat Long' as it's now redundant
df.drop('Lat Long', axis=1, inplace=True)
Encode Categorical Variables:
python
# Identify categorical columns
categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
categorical_cols.remove('CustomerID') # Assuming 'CustomerID' is unique
# Initialize Label Encoder
le = LabelEncoder()
# Apply Label Encoding to binary categorical variables
binary_cols = [col for col in categorical_cols if df[col].nunique() == 2]
for col in binary_cols:
df[col] = le.fit_transform(df[col])
# For multi-class categorical variables, use One-Hot Encoding
multi_cols = [col for col in categorical_cols if df[col].nunique() > 2]
df = pd.get_dummies(df, columns=multi_cols, drop_first=True)
2. Exploratory Data Analysis (EDA)
a. Distribution of CLTV
python
plt.figure(figsize=(10,6))
sns.histplot(df['CLTV'], kde=True, bins=30)
plt.title('Distribution of Customer Lifetime Value (CLTV)')
plt.xlabel('CLTV')
plt.ylabel('Frequency')
plt.show()
b. CLTV vs. Churn
python
plt.figure(figsize=(8,6))
sns.boxplot(x='Churn Value', y='CLTV', data=df)
plt.title('CLTV by Churn Status')
plt.xlabel('Churn')
plt.ylabel('CLTV')
plt.show()
# Alternatively, using violin plot
sns.violinplot(x='Churn Value', y='CLTV', data=df)
plt.title('CLTV Distribution by Churn Status')
plt.xlabel('Churn')
plt.ylabel('CLTV')
plt.show()
Identify variables with high correlation with CLTV.
python
# Sort correlation values
cltv_corr = corr['CLTV'].sort_values(ascending=False)
print(cltv_corr)
# Plot top 10 positively and negatively correlated features
top_features = cltv_corr[1:11].index.tolist()
plt.figure(figsize=(10,6))
sns.barplot(x=cltv_corr[top_features].values, y=top_features)
plt.title('Top 10 Features Positively Correlated with CLTV')
plt.xlabel('Correlation Coefficient')
plt.ylabel('Features')
plt.show()
3. Correlation Analysis
a. Correlation Between CLTV and Churn
Investigate how churn affects CLTV.
python
# Calculate average CLTV for churned vs non-churned customers
cltv_churn = df.groupby('Churn Value')['CLTV'].mean().reset_index()
print(cltv_churn)
# Visualize
sns.barplot(x='Churn Value', y='CLTV', data=cltv_churn)
plt.title('Average CLTV by Churn Status')
plt.xlabel('Churn (0: No, 1: Yes)')
plt.ylabel('Average CLTV')
plt.show()
b. Correlation with Other Behavioral Factors
For example, tenure, services subscribed, etc.
python
# Scatter plot of CLTV vs Tenure
plt.figure(figsize=(10,6))
sns.scatterplot(x='Tenure Months', y='CLTV', hue='Churn Value', data=df)
plt.title('CLTV vs Tenure Months')
plt.xlabel('Tenure (Months)')
plt.ylabel('CLTV')
plt.show()
# Analyze the impact of Internet Service type on CLTV
sns.boxplot(x='Internet Service_Fiber optic', y='CLTV', data=df)
plt.title('CLTV by Internet Service Type')
plt.xlabel('Fiber Optic Service (0: No, 1: Yes)')
plt.ylabel('CLTV')
plt.show()
4. Modeling CLTV and Churn
a. Predicting CLTV with Regression Models
i. Prepare Data for Regression
python
# Define features and target
X = df.drop(['CustomerID', 'CLTV', 'Churn Label', 'Churn Reason'], axis=1)
y = df['CLTV']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Feature Scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
Analyze which features are most important in predicting CLTV and Churn.
python
# For Random Forest Regressor
importances = rf_reg.feature_importances_
feature_names = X.columns
feature_importance = pd.Series(importances, index=feature_names).sort_values(ascending=False)
plt.figure(figsize=(12,8))
sns.barplot(x=feature_importance[:20], y=feature_importance.index[:20])
plt.title('Top 20 Feature Importances for CLTV')
plt.xlabel('Importance Score')
plt.ylabel('Features')
plt.show()
# For Random Forest Classifier
importances_clf = rf_clf.feature_importances_
feature_importance_clf = pd.Series(importances_clf, index=X_churn.columns).sort_values(ascending=False)
plt.figure(figsize=(12,8))
sns.barplot(x=feature_importance_clf[:20], y=feature_importance_clf.index[:20])
plt.title('Top 20 Feature Importances for Churn')
plt.xlabel('Importance Score')
plt.ylabel('Features')
plt.show()
5. Optimization Strategies
Based on the analysis and modeling results, here are some optimization strategies to enhance CLTV:
a. Improve Retention of High CLTV Customers
Identify High CLTV Segments: Use the model to segment customers with high predicted CLTV.
Personalized Communication: Engage high-value customers with personalized offers and loyalty programs.
Proactive Support: Offer premium support services to prevent churn.
b. Reduce Churn Among At-Risk Customers
Targeted Interventions: Use churn prediction models to identify at-risk customers and intervene with incentives (e.g., discounts, service upgrades).
Improve Service Quality: Enhance areas that contribute to churn, such as better tech support or more reliable services.
Flexible Contracts: Offer more flexible contract terms to reduce the likelihood of churn.
c. Upsell and Cross-Sell Additional Services
Bundle Services: Encourage customers to subscribe to additional services (e.g., Internet Security, Online Backup) that are correlated with higher CLTV.
Personalized Offers: Based on customer behavior and preferences, tailor offers that align with their needs.
d. Optimize Pricing Strategies
Analyze Pricing Impact: Use the regression model to understand how monthly charges impact CLTV and churn.
Dynamic Pricing: Implement pricing strategies that maximize revenue without significantly increasing churn.
e. Enhance Customer Experience
Feedback Mechanisms: Collect and analyze customer feedback to identify pain points affecting CLTV.
Improve Onboarding: Ensure a smooth onboarding process to increase initial satisfaction and tenure.
f. Leverage Geographic Insights
Location-Based Strategies: Since the dataset includes geographical data (Latitude, Longitude, Zip Code), tailor marketing and service strategies based on regional preferences and behaviors.
g. Monitor and Iterate
Continuous Monitoring: Regularly track CLTV and churn metrics to assess the effectiveness of implemented strategies.
Model Updates: Update predictive models periodically with new data to maintain accuracy.
Conclusion
By systematically analyzing the dataset, building predictive models, and identifying key factors influencing Customer Lifetime Value and churn, we can implement targeted strategies to optimize CLTV. The combination of data-driven insights and strategic interventions will help in maximizing customer value and ensuring long-term business success.
Complete Python Code Example
Below is a consolidated Python script that encapsulates the steps outlined above. This script is intended for illustrative purposes and may require adjustments based on the actual dataset and environment.
python
Note: Ensure that the dataset customer_data.csv is correctly formatted and available in the working directory. Additionally, install all necessary Python packages using pip if they are not already installed.
By following this comprehensive approach, you can effectively analyze factors affecting Customer Lifetime Value, understand its correlation with churn and other behaviors, and implement data-driven strategies to optimize CLTV in your organization.
Not yet included in a published release.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.metrics import mean_squared_error, r2_score, classification_report, confusion_matrix, roc_auc_score
# Load the dataset
df = pd.read_csv('customer_data.csv')
# Handle missing 'Churn Reason'
df['Churn Reason'] = df['Churn Reason'].fillna('Not Churned')
# Convert 'Total Charges' to numeric
df['Total Charges'] = pd.to_numeric(df['Total Charges'], errors='coerce')
df['Total Charges'] = df['Total Charges'].fillna(df['Monthly Charges'] * df['Tenure Months'])
# Split 'Lat Long' into 'Latitude' and 'Longitude'
df[['Latitude', 'Longitude']] = df['Lat Long'].str.split(',', expand=True).astype(float)
df.drop('Lat Long', axis=1, inplace=True)
# Encode categorical variables
categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
categorical_cols.remove('CustomerID')
le = LabelEncoder()
binary_cols = [col for col in categorical_cols if df[col].nunique() == 2]
for col in binary_cols:
df[col] = le.fit_transform(df[col])
multi_cols = [col for col in categorical_cols if df[col].nunique() > 2]
df = pd.get_dummies(df, columns=multi_cols, drop_first=True)
# EDA: Distribution of CLTV
plt.figure(figsize=(10,6))
sns.histplot(df['CLTV'], kde=True, bins=30)
plt.title('Distribution of Customer Lifetime Value (CLTV)')
plt.xlabel('CLTV')
plt.ylabel('Frequency')
plt.show()
# EDA: CLTV vs Churn
plt.figure(figsize=(8,6))
sns.boxplot(x='Churn Value', y='CLTV', data=df)
plt.title('CLTV by Churn Status')
plt.xlabel('Churn')
plt.ylabel('CLTV')
plt.show()
# Correlation Heatmap
plt.figure(figsize=(20,15))
corr = df.corr()
sns.heatmap(corr, annot=False, cmap='coolwarm')
plt.title('Correlation Heatmap')
plt.show()
# Top Features for CLTV
cltv_corr = corr['CLTV'].sort_values(ascending=False)
top_features = cltv_corr[1:11].index.tolist()
plt.figure(figsize=(10,6))
sns.barplot(x=cltv_corr[top_features].values, y=top_features)
plt.title('Top 10 Features Positively Correlated with CLTV')
plt.xlabel('Correlation Coefficient')
plt.ylabel('Features')
plt.show()
# Predicting CLTV with Random Forest Regressor
X = df.drop(['CustomerID', 'CLTV', 'Churn Label', 'Churn Reason'], axis=1)
y = df['CLTV']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
rf_reg = RandomForestRegressor(n_estimators=100, random_state=42)
rf_reg.fit(X_train_scaled, y_train)
y_pred_rf = rf_reg.predict(X_test_scaled)
print('Random Forest RMSE:', np.sqrt(mean_squared_error(y_test, y_pred_rf)))
print('Random Forest R²:', r2_score(y_test, y_pred_rf))
# Predicting Churn with Random Forest Classifier
X_churn = df.drop(['CustomerID', 'Churn Label', 'Churn Reason', 'CLTV'], axis=1)
y_churn = df['Churn Value']
X_train_c, X_test_c, y_train_c, y_test_c = train_test_split(X_churn, y_churn, test_size=0.2, random_state=42)
X_train_c_scaled = scaler.fit_transform(X_train_c)
X_test_c_scaled = scaler.transform(X_test_c)
rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)
rf_clf.fit(X_train_c_scaled, y_train_c)
y_pred_rf_clf = rf_clf.predict(X_test_c_scaled)
y_pred_proba_rf_clf = rf_clf.predict_proba(X_test_c_scaled)[:,1]
print(classification_report(y_test_c, y_pred_rf_clf))
print('ROC AUC:', roc_auc_score(y_test_c, y_pred_proba_rf_clf))
# Feature Importance for CLTV
importances = rf_reg.feature_importances_
feature_names = X.columns
feature_importance = pd.Series(importances, index=feature_names).sort_values(ascending=False)
plt.figure(figsize=(12,8))
sns.barplot(x=feature_importance[:20], y=feature_importance.index[:20])
plt.title('Top 20 Feature Importances for CLTV')
plt.xlabel('Importance Score')
plt.ylabel('Features')
plt.show()
# Feature Importance for Churn
importances_clf = rf_clf.feature_importances_
feature_importance_clf = pd.Series(importances_clf, index=X_churn.columns).sort_values(ascending=False)
plt.figure(figsize=(12,8))
sns.barplot(x=feature_importance_clf[:20], y=feature_importance_clf.index[:20])
plt.title('Top 20 Feature Importances for Churn')
plt.xlabel('Importance Score')
plt.ylabel('Features')
plt.show()
# Analysis and Strategy Implementation would follow based on above insights