Group Part II: Data Modeling and Visualization

Q9: Data Cleaning and Preparation Problem Statement: Analyzing Customer Churn in a Telecommunications Company Dataset: "Telecom_Customer_Churn.csv" Description: The dataset contains information about customers of a telecommunications company and whether they have churned (i.e., discontinued their services). The dataset includes various attributes of the customers, such as their demographics, usage patterns, and account information. The goal is to perform data cleaning and preparation to gain insights into the factors that contribute to customer churn. Tasks to Perform: 1. Import the "Telecom_Customer_Churn.csv" dataset. 2. Explore the dataset to understand its structure and content. 3. Handle missing values in the dataset, deciding on an appropriate strategy. 4. Remove any duplicate records from the dataset. 5. Check for inconsistent data, such as inconsistent formatting or spelling variations, and standardize it. 6. Convert columns to the correct data types as needed. 7. Identify and handle outliers in the data. 8. Perform feature engineering, creating new features that may be relevant to predicting customer churn. 9. Normalize or scale the data if necessary. 10. Split the dataset into training and testing sets for further analysis. 11. Export the cleaned dataset for future analysis or modeling.

Data Cleaning and Preparation

Solution and implementation for Q9 from Data Modeling & Visualization (dmv).

9_telecom_churn_cleaning.ipynb Download

DMV Assignment 9: Customer Churn (Data Cleaning and Preparation)

Analyze customer churn dataset, clean and preprocess data, perform feature engineering, encode categoricals, split, scale, and export cleaned dataset.

Code Cell 1
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
Code Cell 2
# Load and explore data
df = pd.read_csv("Telecom_Customer_Churn.csv")
print("First 5 records:")
print(df.head())
print("\nDataset Info:")
print(df.info())
print("\nMissing values count:")
print(df.isnull().sum())
First 5 records:
   customerID  gender  SeniorCitizen Partner Dependents  tenure PhoneService  \
0  7590-VHVEG  Female              0     Yes         No       1           No   
1  5575-GNVDE    Male              0      No         No      34          Yes   
2  3668-QPYBK    Male              0      No         No       2          Yes   
3  7795-CFOCW    Male              0      No         No      45           No   
4  9237-HQITU  Female              0      No         No       2          Yes   

      MultipleLines InternetService OnlineSecurity  ... DeviceProtection  \
0  No phone service             DSL             No  ...               No   
1                No             DSL            Yes  ...              Yes   
2                No             DSL            Yes  ...               No   
3  No phone service             DSL            Yes  ...              Yes   
4                No     Fiber optic             No  ...               No   

  TechSupport StreamingTV StreamingMovies        Contract PaperlessBilling  \
0          No          No              No  Month-to-month              Yes   
1          No          No              No        One year               No   
2          No          No              No  Month-to-month              Yes   
3         Yes          No              No        One year               No   
4          No          No              No  Month-to-month              Yes   

               PaymentMethod MonthlyCharges  TotalCharges  Churn  
0           Electronic check          29.85         29.85     No  
1               Mailed check          56.95       1889.50     No  
2               Mailed check          53.85        108.15    Yes  
3  Bank transfer (automatic)          42.30       1840.75     No  
4           Electronic check          70.70        151.15    Yes  

[5 rows x 21 columns]

Dataset Info:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 21 columns):
 #   Column            Non-Null Count  Dtype  
---  ------            --------------  -----  
 0   customerID        10 non-null     object 
 1   gender            10 non-null     object 
 2   SeniorCitizen     10 non-null     int64  
 3   Partner           10 non-null     object 
 4   Dependents        10 non-null     object 
 5   tenure            10 non-null     int64  
 6   PhoneService      10 non-null     object 
 7   MultipleLines     10 non-null     object 
 8   InternetService   10 non-null     object 
 9   OnlineSecurity    10 non-null     object 
 10  OnlineBackup      10 non-null     object 
 11  DeviceProtection  10 non-null     object 
 12  TechSupport       10 non-null     object 
 13  StreamingTV       10 non-null     object 
 14  StreamingMovies   10 non-null     object 
 15  Contract          10 non-null     object 
 16  PaperlessBilling  10 non-null     object 
 17  PaymentMethod     10 non-null     object 
 18  MonthlyCharges    10 non-null     float64
 19  TotalCharges      10 non-null     float64
 20  Churn             10 non-null     object 
dtypes: float64(2), int64(2), object(17)
memory usage: 1.8+ KB
None

Missing values count:
customerID          0
gender              0
SeniorCitizen       0
Partner             0
Dependents          0
tenure              0
PhoneService        0
MultipleLines       0
InternetService     0
OnlineSecurity      0
OnlineBackup        0
DeviceProtection    0
TechSupport         0
StreamingTV         0
StreamingMovies     0
Contract            0
PaperlessBilling    0
PaymentMethod       0
MonthlyCharges      0
TotalCharges        0
Churn               0
dtype: int64
Code Cell 3
# Clean data
df.drop_duplicates(inplace=True)
df.replace(r"^\\s*$", pd.NA, regex=True, inplace=True)
df.dropna(inplace=True)
print("Shape after cleaning:", df.shape)
Shape after cleaning: (10, 21)
Code Cell 4
# Convert numeric columns & feature engineering
if "customerID" in df.columns:
    df.drop(columns=["customerID"], inplace=True)

for col in df.columns:
    df[col] = pd.to_numeric(df[col], errors="ignore")

if "tenure" in df.columns:
    df["CustomerYears"] = df["tenure"] / 12
    print("Feature 'CustomerYears' created successfully:")
    print(df[["tenure", "CustomerYears"]].head())
Feature 'CustomerYears' created successfully:
   tenure  CustomerYears
0       1       0.083333
1      34       2.833333
2       2       0.166667
3      45       3.750000
4       2       0.166667
Code Cell 5
# Encode categorical columns
df_encoded = pd.get_dummies(df, drop_first=True, dtype=float)
print(df_encoded.columns)


# Separate X and y
X = df_encoded.drop(columns=["Churn_Yes"])
y = df_encoded["Churn_Yes"]

# Split data
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

print("Training data:", X_train.shape)
print("Testing data:", X_test.shape)
Index(['SeniorCitizen', 'tenure', 'MonthlyCharges', 'TotalCharges',
       'CustomerYears', 'gender_Male', 'Partner_Yes', 'Dependents_Yes',
       'PhoneService_Yes', 'MultipleLines_No phone service',
       'MultipleLines_Yes', 'InternetService_Fiber optic',
       'OnlineSecurity_Yes', 'OnlineBackup_Yes', 'DeviceProtection_Yes',
       'TechSupport_Yes', 'StreamingTV_Yes', 'StreamingMovies_Yes',
       'Contract_One year', 'Contract_Two year', 'PaperlessBilling_Yes',
       'PaymentMethod_Credit card (automatic)',
       'PaymentMethod_Electronic check', 'PaymentMethod_Mailed check',
       'Churn_Yes'],
      dtype='object')
Training data: (8, 24)
Testing data: (2, 24)
Code Cell 6
# Scale features and export cleaned dataset
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("Feature scaling completed.")

df.to_csv("cleaned_churn.csv", index=False)
print("Data cleaning completed! Exported to cleaned_churn.csv")
Feature scaling completed.
Data cleaning completed! Exported to cleaned_churn.csv
Telecom_Customer_Churn.csv Download
customerID,gender,SeniorCitizen,Partner,Dependents,tenure,PhoneService,MultipleLines,InternetService,OnlineSecurity,OnlineBackup,DeviceProtection,TechSupport,StreamingTV,StreamingMovies,Contract,PaperlessBilling,PaymentMethod,MonthlyCharges,TotalCharges,Churn
7590-VHVEG,Female,0,Yes,No,1,No,No phone service,DSL,No,Yes,No,No,No,No,Month-to-month,Yes,Electronic check,29.85,29.85,No
5575-GNVDE,Male,0,No,No,34,Yes,No,DSL,Yes,No,Yes,No,No,No,One year,No,Mailed check,56.95,1889.5,No
3668-QPYBK,Male,0,No,No,2,Yes,No,DSL,Yes,Yes,No,No,No,No,Month-to-month,Yes,Mailed check,53.85,108.15,Yes
7795-CFOCW,Male,0,No,No,45,No,No phone service,DSL,Yes,No,Yes,Yes,No,No,One year,No,Bank transfer (automatic),42.30,1840.75,No
9237-HQITU,Female,0,No,No,2,Yes,No,Fiber optic,No,No,No,No,No,No,Month-to-month,Yes,Electronic check,70.70,151.15,Yes
9305-CDSKC,Female,0,No,No,8,Yes,Yes,Fiber optic,No,No,Yes,No,Yes,Yes,Month-to-month,Yes,Electronic check,99.65,820.5,Yes
1452-ILZYY,Female,0,No,Yes,22,Yes,Yes,Fiber optic,No,Yes,No,No,Yes,No,One year,Yes,Credit card (automatic),89.10,1949.4,No
6713-OKOMC,Female,0,Yes,No,10,Yes,No,DSL,Yes,No,No,No,No,No,Month-to-month,No,Mailed check,29.75,301.9,No
7892-POKVL,Male,0,No,No,28,Yes,Yes,Fiber optic,No,No,Yes,Yes,Yes,Yes,Month-to-month,Yes,Electronic check,104.80,3046.4,Yes
6388-TABGU,Male,0,Yes,Yes,62,Yes,Yes,DSL,Yes,Yes,Yes,Yes,Yes,Yes,Two year,Yes,Credit card (automatic),84.80,5257.6,No
cleaned_churn.csv Download
gender,SeniorCitizen,Partner,Dependents,tenure,PhoneService,MultipleLines,InternetService,OnlineSecurity,OnlineBackup,DeviceProtection,TechSupport,StreamingTV,StreamingMovies,Contract,PaperlessBilling,PaymentMethod,MonthlyCharges,TotalCharges,Churn,CustomerYears
Female,0,Yes,No,1,No,No phone service,DSL,No,Yes,No,No,No,No,Month-to-month,Yes,Electronic check,29.85,29.85,No,0.08333333333333333
Male,0,No,No,34,Yes,No,DSL,Yes,No,Yes,No,No,No,One year,No,Mailed check,56.95,1889.5,No,2.8333333333333335
Male,0,No,No,2,Yes,No,DSL,Yes,Yes,No,No,No,No,Month-to-month,Yes,Mailed check,53.85,108.15,Yes,0.16666666666666666
Male,0,No,No,45,No,No phone service,DSL,Yes,No,Yes,Yes,No,No,One year,No,Bank transfer (automatic),42.3,1840.75,No,3.75
Female,0,No,No,2,Yes,No,Fiber optic,No,No,No,No,No,No,Month-to-month,Yes,Electronic check,70.7,151.15,Yes,0.16666666666666666
Female,0,No,No,8,Yes,Yes,Fiber optic,No,No,Yes,No,Yes,Yes,Month-to-month,Yes,Electronic check,99.65,820.5,Yes,0.6666666666666666
Female,0,No,Yes,22,Yes,Yes,Fiber optic,No,Yes,No,No,Yes,No,One year,Yes,Credit card (automatic),89.1,1949.4,No,1.8333333333333333
Female,0,Yes,No,10,Yes,No,DSL,Yes,No,No,No,No,No,Month-to-month,No,Mailed check,29.75,301.9,No,0.8333333333333334
Male,0,No,No,28,Yes,Yes,Fiber optic,No,No,Yes,Yes,Yes,Yes,Month-to-month,Yes,Electronic check,104.8,3046.4,Yes,2.3333333333333335
Male,0,Yes,Yes,62,Yes,Yes,DSL,Yes,Yes,Yes,Yes,Yes,Yes,Two year,Yes,Credit card (automatic),84.8,5257.6,No,5.166666666666667

Other Questions in Data Modeling & Visualization

See All Available Questions
Download