For a dataset which looks like above and has no empty values, please perform the following analytics in Python:
Descriptive Statistics
Customer Demographics: Analyze the distribution of customers by gender, age (Senior Citizen), and geographic location (Country, State, City).
Service Usage: Summarize the usage of different services (Phone Service, Internet Service, etc.) and additional features (Online Security, Streaming TV, etc.).
Billing and Payment Methods: Examine the distribution of billing types (Paperless Billing) and payment methods.
Churn Analysis
Churn Rate: Calculate the overall churn rate and segment it by different demographic and service usage categories.
Churn Reasons: Analyze the reasons for churn (Churn Reason) to identify common issues leading to customer attrition.
Churn Score and CLTV: Evaluate the relationship between Churn Score, Customer Lifetime Value (CLTV), and actual churn (Churn Label).
Segmentation Analysis
Geographic Segmentation: Compare churn rates and service usage across different geographic regions.
Demographic Segmentation: Analyze churn rates and service preferences by gender, senior citizen status, and presence of partners/dependents.
Service Segmentation: Segment customers based on the types of services they use and analyze churn rates within these segments.
Tenure Analysis
Tenure vs. Churn: Investigate the relationship between tenure (Tenure Months) and churn rate.
Tenure vs. Service Usage: Analyze how service usage patterns change with tenure.
Feature Importance
Correlation Analysis: Identify correlations between different features (e.g., Monthly Charges, Total Charges, Contract Type) and churn.
Predictive Modeling: Build predictive models (e.g., logistic regression, decision trees) to identify the most important features contributing to churn.
Customer Lifetime Value (CLTV) Analysis
CLTV Distribution: Analyze the distribution of CLTV across different customer segments.
CLTV vs. Churn: Investigate the relationship between CLTV and churn rate to identify high-value customers at risk of churning.
Assistant
Geospatial Analysis
Churn Hotspots: Use Latitude and Longitude data to identify geographic hotspots with high churn rates.
Service Availability: Analyze the availability and usage of different services across geographic regions.
Time Series Analysis
Trend Analysis: Analyze trends in churn rates, service usage, and customer demographics over time.
Seasonality: Identify any seasonal patterns in churn rates and service usage.
Customer Feedback Analysis
Sentiment Analysis: If available, analyze customer feedback and sentiment to understand the reasons behind churn and identify areas for improvement.
To perform comprehensive analytics on your customer dataset, we'll use Python along with powerful libraries such as pandas, numpy, matplotlib, seaborn, and scikit-learn. Below is a step-by-step guide covering each of the requested analysis areas.
1. Setup and Data Loading
First, let's import the necessary libraries and load the dataset.
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# For predictive modeling
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
# Load the dataset
# Assuming the data is stored in 'customer_data.csv'
df = pd.read_csv('customer_data.csv')
# Display the first few rows
print(df.head())
2. Descriptive Statistics
a. Customer Demographics
Analyze the distribution of customers by gender, senior citizen status, and geographic location.
python
# Gender Distribution
gender_counts = df['Gender'].value_counts()
plt.figure(figsize=(6,4))
sns.barplot(x=gender_counts.index, y=gender_counts.values, palette='viridis')
plt.title('Customer Distribution by Gender')
plt.ylabel('Count')
plt.show()
# Senior Citizen Distribution
senior_counts = df['Senior Citizen'].value_counts()
plt.figure(figsize=(6,4))
sns.barplot(x=senior_counts.index, y=senior_counts.values, palette='magma')
plt.title('Senior Citizen Distribution')
plt.ylabel('Count')
plt.show()
# Geographic Distribution
# Country
country_counts = df['Country'].value_counts()
plt.figure(figsize=(8,6))
sns.barplot(x=country_counts.index, y=country_counts.values, palette='coolwarm')
plt.title('Customer Distribution by Country')
plt.ylabel('Count')
plt.show()
# State
state_counts = df['State'].value_counts()
plt.figure(figsize=(12,6))
sns.barplot(x=state_counts.index, y=state_counts.values, palette='plasma')
plt.title('Customer Distribution by State')
plt.ylabel('Count')
plt.xticks(rotation=90)
plt.show()
# City
city_counts = df['City'].value_counts()
plt.figure(figsize=(12,6))
sns.barplot(x=city_counts.index, y=city_counts.values, palette='inferno')
plt.title('Customer Distribution by City')
plt.ylabel('Count')
plt.xticks(rotation=90)
plt.show()
b. Service Usage
Summarize the usage of different services and additional features.
python
service_columns = ['Phone Service', 'Multiple Lines', 'Internet Service',
'Online Security', 'Online Backup', 'Device Protection',
'Tech Support', 'Streaming TV', 'Streaming Movies']
for col in service_columns:
counts = df[col].value_counts()
plt.figure(figsize=(6,4))
sns.barplot(x=counts.index, y=counts.values, palette='Set2')
plt.title(f'Distribution of {col}')
plt.ylabel('Count')
plt.show()
c. Billing and Payment Methods
Examine the distribution of billing types and payment methods.
Compare churn rates and service usage across different geographic regions.
python
# Churn Rate by State
churn_state = df.groupby('State')['Churn Label'].value_counts(normalize=True).unstack() * 100
print("Churn Rate by State:\n", churn_state)
# Visualization
churn_state.plot(kind='bar', stacked=True, figsize=(12,8), colormap='viridis')
plt.title('Churn Rate by State')
plt.ylabel('Percentage')
plt.show()
b. Demographic Segmentation
Analyze churn rates and service preferences by gender, senior citizen status, and presence of partners/dependents.
python
# Churn Rate by Partner
churn_partner = df.groupby('Partner')['Churn Label'].value_counts(normalize=True).unstack() * 100
print("Churn Rate by Partner:\n", churn_partner)
# Churn Rate by Dependents
churn_dependents = df.groupby('Dependents')['Churn Label'].value_counts(normalize=True).unstack() * 100
print("Churn Rate by Dependents:\n", churn_dependents)
c. Service Segmentation
Segment customers based on the types of services they use and analyze churn rates within these segments.
python
# Example: Internet Service Types
churn_internet = df.groupby('Internet Service')['Churn Label'].value_counts(normalize=True).unstack() * 100
print("Churn Rate by Internet Service Type:\n", churn_internet)
# Visualization
churn_internet.plot(kind='bar', stacked=True, figsize=(8,6), colormap='Accent')
plt.title('Churn Rate by Internet Service Type')
plt.ylabel('Percentage')
plt.show()
5. Tenure Analysis
a. Tenure vs. Churn
Investigate the relationship between tenure months and churn rate.
python
# Average Tenure by Churn Label
tenure_churn = df.groupby('Churn Label')['Tenure Months'].mean()
print("Average Tenure by Churn Label:\n", tenure_churn)
# Boxplot
plt.figure(figsize=(8,6))
sns.boxplot(x='Churn Label', y='Tenure Months', data=df, palette='Set2')
plt.title('Tenure Months by Churn Label')
plt.show()
b. Tenure vs. Service Usage
Analyze how service usage patterns change with tenure.
python
# Average Tenure by Service Usage
services = ['Phone Service', 'Multiple Lines', 'Internet Service']
for service in services:
plt.figure(figsize=(8,6))
sns.boxplot(x=service, y='Tenure Months', data=df, palette='Pastel1')
plt.title(f'Tenure Months by {service}')
plt.show()
6. Feature Importance
a. Correlation Analysis
Identify correlations between different features and churn.
Analyze the distribution of CLTV across different customer segments.
python
# Histogram of CLTV
plt.figure(figsize=(10,6))
sns.histplot(df['CLTV'], bins=30, kde=True, color='skyblue')
plt.title('CLTV Distribution')
plt.xlabel('Customer Lifetime Value (CLTV)')
plt.ylabel('Frequency')
plt.show()
# CLTV by Gender
plt.figure(figsize=(8,6))
sns.boxplot(x='Gender', y='CLTV', data=df, palette='Set3')
plt.title('CLTV by Gender')
plt.show()
# CLTV by Senior Citizen Status
plt.figure(figsize=(8,6))
sns.boxplot(x='Senior Citizen', y='CLTV', data=df, palette='Set1')
plt.title('CLTV by Senior Citizen Status')
plt.show()
b. CLTV vs. Churn
Investigate the relationship between CLTV and churn rate.
python
# Average CLTV by Churn Label
cltv_churn = df.groupby('Churn Label')['CLTV'].mean()
print("Average CLTV by Churn Label:\n", cltv_churn)
# Boxplot
plt.figure(figsize=(8,6))
sns.boxplot(x='Churn Label', y='CLTV', data=df, palette='coolwarm')
plt.title('CLTV by Churn Label')
plt.show()
8. Geospatial Analysis
a. Churn Hotspots
Identify geographic hotspots with high churn rates.
python
import folium
from folium.plugins import HeatMap
# Calculate churn rate per location
df['Churn_numeric'] = df['Churn Label'].apply(lambda x: 1 if x == 'Yes' else 0)
heat_data = df[['Latitude', 'Longitude', 'Churn_numeric']].groupby(['Latitude', 'Longitude']).sum().reset_index()
# Create a base map
base_map = folium.Map(location=[df['Latitude'].mean(), df['Longitude'].mean()], zoom_start=10)
# Add heatmap
HeatMap(data=heat_data[['Latitude', 'Longitude', 'Churn_numeric']],
radius=10,
max_zoom=13,
gradient={0.4: 'blue', 0.65: 'lime', 1: 'red'}).add_to(base_map)
# Save map to HTML
base_map.save('churn_heatmap.html')
Open the churn_heatmap.html file in a browser to view the churn hotspots.
b. Service Availability
Analyze the availability and usage of different services across geographic regions.
python
# Example: Internet Service Availability by State
internet_service_state = df.groupby(['State', 'Internet Service']).size().unstack().fillna(0)
internet_service_state.plot(kind='bar', stacked=True, figsize=(12,8), colormap='tab20')
plt.title('Internet Service Availability by State')
plt.ylabel('Number of Customers')
plt.show()
9. Time Series Analysis
Note: Ensure the dataset has a time component such as Signup Date or Last Payment Date. Since the provided data does not include such a field, we'll assume Tenure Months can be used as a proxy.
a. Trend Analysis
Analyze trends in churn rates and service usage over time.
python
# Create a 'Tenure Group' (e.g., ranges of tenure months)
df['Tenure Group'] = pd.cut(df['Tenure Months'], bins=[0, 12, 24, 36, 48, 60, 72, 84, 96], labels=['0-12', '13-24', '25-36', '37-48', '49-60', '61-72', '73-84', '85-96'])
# Churn Trend Over Tenure Groups
churn_trend = df.groupby('Tenure Group')['Churn Label'].value_counts(normalize=True).unstack() * 100
churn_trend.plot(kind='line', marker='o', figsize=(10,6))
plt.title('Churn Trend Over Tenure Groups')
plt.ylabel('Churn Rate (%)')
plt.show()
# Service Usage Trend Over Tenure Groups
service_usage_trend = df.groupby('Tenure Group')['Internet Service'].value_counts(normalize=True).unstack() * 100
service_usage_trend.plot(kind='line', marker='o', figsize=(10,6))
plt.title('Internet Service Usage Over Tenure Groups')
plt.ylabel('Usage Percentage (%)')
plt.show()
b. Seasonality
Identify any seasonal patterns in churn rates and service usage.
Without explicit date fields, seasonality analysis isn't feasible. If you have timestamp data, you can extract month or quarter information to perform this analysis.
10. Customer Feedback Analysis
Note: The provided dataset does not include textual customer feedback. If available, you can perform sentiment analysis using NLP libraries.
a. Sentiment Analysis
Assuming there's a Customer Feedback column containing textual feedback.
python
# Install necessary packages
# !pip install nltk
# !pip install textblob
import nltk
from textblob import TextBlob
# Download NLTK data
nltk.download('punkt')
# Example customer feedback
df['Customer Feedback'] = df['Churn Reason'] # Using Churn Reason as a proxy
# Function to calculate sentiment polarity
def get_sentiment(text):
blob = TextBlob(text)
return blob.sentiment.polarity
# Apply sentiment analysis
df['Sentiment'] = df['Customer Feedback'].apply(get_sentiment)
# Visualize Sentiment by Churn Label
plt.figure(figsize=(8,6))
sns.boxplot(x='Churn Label', y='Sentiment', data=df, palette='Set2')
plt.title('Sentiment Analysis by Churn Label')
plt.show()
# Average Sentiment
average_sentiment = df.groupby('Churn Label')['Sentiment'].mean()
print("Average Sentiment by Churn Label:\n", average_sentiment)
For more advanced sentiment analysis, consider using libraries like VADER or transformer-based models from Hugging Face.
Conclusion
This comprehensive analysis provides insights into customer demographics, service usage, billing preferences, churn behavior, and more. By leveraging these insights, you can make informed decisions to improve customer retention, optimize services, and enhance overall customer satisfaction.
Next Steps:
Data Refinement: Ensure data quality by handling outliers, encoding categorical variables appropriately, and scaling numerical features.
Advanced Modeling: Explore ensemble models like Random Forest or Gradient Boosting for better predictive performance.
Deployment: Implement the predictive model into a production environment to flag high-risk customers in real-time.
Actionable Strategies: Develop targeted marketing campaigns, personalized offers, and improved customer service based on the insights gathered.
Feel free to reach out if you need further assistance with any specific part of the analysis!