help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
customer-churn
/
scripts
RSK World
customer-churn
Customer Churn Dataset
scripts
  • __init__.py332 B
  • data_exploration.py7.9 KB
  • data_preprocessing.py9.6 KB
  • feature_selection.py7.5 KB
  • generate_dataset.py5.7 KB
  • hyperparameter_tuning.py8.9 KB
  • model_training.py19.7 KB
data_exploration.py
scripts/data_exploration.py
Raw Download
Find: Go to:
"""
Customer Churn Dataset - Data Exploration Script
================================================
Provided by: RSK World
Website: https://rskworld.in/
Email: help@rskworld.in
Phone: +91 93305 39277
Contact Page: https://rskworld.in/contact.php
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Set style for better visualizations
sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = (12, 6)

def load_data(file_path='../data/customer_churn.csv'):
    """
    Load the customer churn dataset
    
    Args:
        file_path (str): Path to the CSV file
        
    Returns:
        pd.DataFrame: Loaded dataset
    """
    df = pd.read_csv(file_path, comment="#", na_values=["", "NA", "NaN"])
    return df

def basic_info(df):
    """
    Display basic information about the dataset
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("=" * 60)
    print("DATASET BASIC INFORMATION")
    print("=" * 60)
    print(f"\nDataset Shape: {df.shape}")
    print(f"Number of Rows: {df.shape[0]}")
    print(f"Number of Columns: {df.shape[1]}")
    
    print("\n" + "-" * 60)
    print("DATASET INFO:")
    print("-" * 60)
    print(df.info())
    
    print("\n" + "-" * 60)
    print("FIRST 5 ROWS:")
    print("-" * 60)
    print(df.head())
    
    print("\n" + "-" * 60)
    print("DATASET STATISTICS:")
    print("-" * 60)
    print(df.describe())

def missing_values(df):
    """
    Check for missing values in the dataset
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("MISSING VALUES ANALYSIS")
    print("=" * 60)
    missing = df.isnull().sum()
    missing_percent = (missing / len(df)) * 100
    missing_df = pd.DataFrame({
        'Missing Count': missing,
        'Missing Percentage': missing_percent
    })
    missing_df = missing_df[missing_df['Missing Count'] > 0]
    
    if len(missing_df) > 0:
        print(missing_df)
    else:
        print("No missing values found!")

def churn_analysis(df):
    """
    Analyze churn distribution
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("CHURN ANALYSIS")
    print("=" * 60)
    
    churn_counts = df['Churn'].value_counts()
    churn_percent = df['Churn'].value_counts(normalize=True) * 100
    
    print("\nChurn Distribution:")
    print(churn_counts)
    print("\nChurn Percentage:")
    print(churn_percent)
    
    # Visualize churn distribution
    plt.figure(figsize=(10, 6))
    plt.subplot(1, 2, 1)
    churn_counts.plot(kind='bar', color=['green', 'red'])
    plt.title('Churn Distribution')
    plt.xlabel('Churn Status')
    plt.ylabel('Count')
    plt.xticks(rotation=0)
    
    plt.subplot(1, 2, 2)
    churn_percent.plot(kind='pie', autopct='%1.1f%%', colors=['green', 'red'])
    plt.title('Churn Percentage')
    plt.ylabel('')
    
    plt.tight_layout()
    plt.savefig('../output/churn_distribution.png')
    plt.show()

def demographic_analysis(df):
    """
    Analyze demographic features
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("DEMOGRAPHIC ANALYSIS")
    print("=" * 60)
    
    # Gender distribution
    print("\nGender Distribution:")
    print(df['Gender'].value_counts())
    
    # Age distribution
    print("\nAge Statistics:")
    print(df['Age'].describe())
    
    # Visualize demographics
    fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    
    # Gender distribution
    df['Gender'].value_counts().plot(kind='bar', ax=axes[0, 0], color=['blue', 'pink'])
    axes[0, 0].set_title('Gender Distribution')
    axes[0, 0].set_xlabel('Gender')
    axes[0, 0].set_ylabel('Count')
    
    # Age distribution
    df['Age'].hist(bins=20, ax=axes[0, 1], color='skyblue')
    axes[0, 1].set_title('Age Distribution')
    axes[0, 1].set_xlabel('Age')
    axes[0, 1].set_ylabel('Frequency')
    
    # Tenure distribution
    df['Tenure'].hist(bins=20, ax=axes[1, 0], color='lightgreen')
    axes[1, 0].set_title('Tenure Distribution')
    axes[1, 0].set_xlabel('Tenure (months)')
    axes[1, 0].set_ylabel('Frequency')
    
    # Account type distribution
    df['AccountType'].value_counts().plot(kind='bar', ax=axes[1, 1], color='orange')
    axes[1, 1].set_title('Account Type Distribution')
    axes[1, 1].set_xlabel('Account Type')
    axes[1, 1].set_ylabel('Count')
    axes[1, 1].tick_params(axis='x', rotation=45)
    
    plt.tight_layout()
    plt.savefig('../output/demographic_analysis.png')
    plt.show()

def usage_billing_analysis(df):
    """
    Analyze usage and billing patterns
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("USAGE & BILLING ANALYSIS")
    print("=" * 60)
    
    print("\nMonthly Usage Statistics:")
    print(df['MonthlyUsage'].describe())
    
    print("\nBilling Amount Statistics:")
    print(df['BillingAmount'].describe())
    
    # Visualize usage and billing
    fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    
    # Monthly usage distribution
    df['MonthlyUsage'].hist(bins=30, ax=axes[0, 0], color='purple')
    axes[0, 0].set_title('Monthly Usage Distribution')
    axes[0, 0].set_xlabel('Monthly Usage')
    axes[0, 0].set_ylabel('Frequency')
    
    # Billing amount distribution
    df['BillingAmount'].hist(bins=30, ax=axes[0, 1], color='teal')
    axes[0, 1].set_title('Billing Amount Distribution')
    axes[0, 1].set_xlabel('Billing Amount ($)')
    axes[0, 1].set_ylabel('Frequency')
    
    # Usage vs Churn
    df.boxplot(column='MonthlyUsage', by='Churn', ax=axes[1, 0])
    axes[1, 0].set_title('Monthly Usage by Churn Status')
    axes[1, 0].set_xlabel('Churn Status')
    axes[1, 0].set_ylabel('Monthly Usage')
    
    # Billing vs Churn
    df.boxplot(column='BillingAmount', by='Churn', ax=axes[1, 1])
    axes[1, 1].set_title('Billing Amount by Churn Status')
    axes[1, 1].set_xlabel('Churn Status')
    axes[1, 1].set_ylabel('Billing Amount ($)')
    
    plt.tight_layout()
    plt.savefig('../output/usage_billing_analysis.png')
    plt.show()

def correlation_analysis(df):
    """
    Analyze correlations between numerical features
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("CORRELATION ANALYSIS")
    print("=" * 60)
    
    # Select numerical columns
    numerical_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    
    if 'CustomerID' in numerical_cols:
        numerical_cols.remove('CustomerID')
    
    correlation_matrix = df[numerical_cols].corr()
    
    print("\nCorrelation Matrix:")
    print(correlation_matrix)
    
    # Visualize correlation matrix
    plt.figure(figsize=(10, 8))
    sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0,
                square=True, linewidths=1, cbar_kws={"shrink": 0.8})
    plt.title('Correlation Matrix of Numerical Features')
    plt.tight_layout()
    plt.savefig('../output/correlation_matrix.png')
    plt.show()

def main():
    """
    Main function to run all analyses
    """
    print("Customer Churn Dataset - Data Exploration")
    print("Provided by: RSK World (https://rskworld.in/)")
    print("-" * 60)
    
    # Load data
    df = load_data()
    
    # Run analyses
    basic_info(df)
    missing_values(df)
    churn_analysis(df)
    demographic_analysis(df)
    usage_billing_analysis(df)
    correlation_analysis(df)
    
    print("\n" + "=" * 60)
    print("ANALYSIS COMPLETE")
    print("=" * 60)
    print("\nFor more information, visit: https://rskworld.in/")
    print("Contact: help@rskworld.in | +91 93305 39277")

if __name__ == "__main__":
    main()

280 lines•7.9 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer