Data Cleaning

Code
# Import Libraries
from nbdev.showdoc import *
import pandas as pd
import numpy as np
from pandas_profiling import ProfileReport
from datetime import datetime

import warnings
warnings.filterwarnings('ignore')
import re

# Load Dataset
df=pd.read_csv('Finance Data/train.csv')

Delete unwanted columns

Code
del df['ID'] # Identification 
del df['SSN'] # SSN (social security number of a person)
Code
df
Customer_ID Month Name Age Occupation Annual_Income Monthly_Inhand_Salary Num_Bank_Accounts Num_Credit_Card Interest_Rate ... Credit_Mix Outstanding_Debt Credit_Utilization_Ratio Credit_History_Age Payment_of_Min_Amount Total_EMI_per_month Amount_invested_monthly Payment_Behaviour Monthly_Balance Credit_Score
0 CUS_0xd40 January Aaron Maashoh 23 Scientist 19114.12 1824.843333 3 4 3 ... _ 809.98 26.822620 22 Years and 1 Months No 49.574949 80.41529543900253 High_spent_Small_value_payments 312.49408867943663 Good
1 CUS_0xd40 February Aaron Maashoh 23 Scientist 19114.12 NaN 3 4 3 ... Good 809.98 31.944960 NaN No 49.574949 118.28022162236736 Low_spent_Large_value_payments 284.62916249607184 Good
2 CUS_0xd40 March Aaron Maashoh -500 Scientist 19114.12 NaN 3 4 3 ... Good 809.98 28.609352 22 Years and 3 Months No 49.574949 81.699521264648 Low_spent_Medium_value_payments 331.2098628537912 Good
3 CUS_0xd40 April Aaron Maashoh 23 Scientist 19114.12 NaN 3 4 3 ... Good 809.98 31.377862 22 Years and 4 Months No 49.574949 199.4580743910713 Low_spent_Small_value_payments 223.45130972736786 Good
4 CUS_0xd40 May Aaron Maashoh 23 Scientist 19114.12 1824.843333 3 4 3 ... Good 809.98 24.797347 22 Years and 5 Months No 49.574949 41.420153086217326 High_spent_Medium_value_payments 341.48923103222177 Good
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
99995 CUS_0x942c April Nicks 25 Mechanic 39628.99 3359.415833 4 6 7 ... _ 502.38 34.663572 31 Years and 6 Months No 35.104023 60.97133255718485 High_spent_Large_value_payments 479.866228 Poor
99996 CUS_0x942c May Nicks 25 Mechanic 39628.99 3359.415833 4 6 7 ... _ 502.38 40.565631 31 Years and 7 Months No 35.104023 54.18595028760385 High_spent_Medium_value_payments 496.65161 Poor
99997 CUS_0x942c June Nicks 25 Mechanic 39628.99 3359.415833 4 6 5729 ... Good 502.38 41.255522 31 Years and 8 Months No 35.104023 24.02847744864441 High_spent_Large_value_payments 516.809083 Poor
99998 CUS_0x942c July Nicks 25 Mechanic 39628.99 3359.415833 4 6 7 ... Good 502.38 33.638208 31 Years and 9 Months No 35.104023 251.67258219721603 Low_spent_Large_value_payments 319.164979 Standard
99999 CUS_0x942c August Nicks 25 Mechanic 39628.99_ 3359.415833 4 6 7 ... Good 502.38 34.192463 31 Years and 10 Months No 35.104023 167.1638651610451 !@9#%8 393.673696 Poor

100000 rows × 26 columns

Remove everything except numbers

Code
#export
def keep_num(val):
    try : 
        return float(re.sub("[^-\d.]","",val))
    except :
        return np.nan
Code
num_cols=['Age', 'Annual_Income', 'Num_of_Loan', 'Num_of_Delayed_Payment', 'Changed_Credit_Limit', 'Amount_invested_monthly', 'Outstanding_Debt' , 'Monthly_Balance']
    
for col in num_cols:
    df[col]=df[col].apply(keep_num)
Code
df.head()
Customer_ID Month Name Age Occupation Annual_Income Monthly_Inhand_Salary Num_Bank_Accounts Num_Credit_Card Interest_Rate ... Credit_Mix Outstanding_Debt Credit_Utilization_Ratio Credit_History_Age Payment_of_Min_Amount Total_EMI_per_month Amount_invested_monthly Payment_Behaviour Monthly_Balance Credit_Score
0 CUS_0xd40 January Aaron Maashoh 23.0 Scientist 19114.12 1824.843333 3 4 3 ... _ 809.98 26.822620 22 Years and 1 Months No 49.574949 80.415295 High_spent_Small_value_payments 312.494089 Good
1 CUS_0xd40 February Aaron Maashoh 23.0 Scientist 19114.12 NaN 3 4 3 ... Good 809.98 31.944960 NaN No 49.574949 118.280222 Low_spent_Large_value_payments 284.629162 Good
2 CUS_0xd40 March Aaron Maashoh -500.0 Scientist 19114.12 NaN 3 4 3 ... Good 809.98 28.609352 22 Years and 3 Months No 49.574949 81.699521 Low_spent_Medium_value_payments 331.209863 Good
3 CUS_0xd40 April Aaron Maashoh 23.0 Scientist 19114.12 NaN 3 4 3 ... Good 809.98 31.377862 22 Years and 4 Months No 49.574949 199.458074 Low_spent_Small_value_payments 223.451310 Good
4 CUS_0xd40 May Aaron Maashoh 23.0 Scientist 19114.12 1824.843333 3 4 3 ... Good 809.98 24.797347 22 Years and 5 Months No 49.574949 41.420153 High_spent_Medium_value_payments 341.489231 Good

5 rows × 26 columns

Split loan type column

Code
loan_t=df['Type_of_Loan'].drop_duplicates().str.split(',',expand=True)
loan_type_ls=loan_t[0].drop_duplicates().dropna()
for i in loan_type_ls: 
    df[i] = df['Type_of_Loan'].str.contains(i)
Code
# filter negative age
df=df[(df['Age']>18) & (df['Age']<120)]
# filter negative num of bank account
df=df[df['Num_Bank_Accounts']>0]
# filter negative num of loan
df=df[df['Num_of_Loan']>0]
# filter negative num of delayed payment
df=df[df['Num_of_Delayed_Payment']>0]
# filter negative monthly balance
df=df[df['Monthly_Balance']>0]
# filter 0 or negative number of credit cards
df=df[df['Num_Credit_Card']>0]

df
Customer_ID Month Name Age Occupation Annual_Income Monthly_Inhand_Salary Num_Bank_Accounts Num_Credit_Card Interest_Rate ... Credit_Score Auto Loan Credit-Builder Loan Not Specified Personal Loan Payday Loan Mortgage Loan Home Equity Loan Debt Consolidation Loan Student Loan
0 CUS_0xd40 January Aaron Maashoh 23.0 Scientist 19114.12 1824.843333 3 4 3 ... Good True True False True False False True False False
3 CUS_0xd40 April Aaron Maashoh 23.0 Scientist 19114.12 NaN 3 4 3 ... Good True True False True False False True False False
5 CUS_0xd40 June Aaron Maashoh 23.0 Scientist 19114.12 NaN 3 4 3 ... Good True True False True False False True False False
6 CUS_0xd40 July Aaron Maashoh 23.0 Scientist 19114.12 1824.843333 3 4 3 ... Good True True False True False False True False False
7 CUS_0xd40 August NaN 23.0 Scientist 19114.12 1824.843333 3 4 3 ... Standard True True False True False False True False False
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
98284 CUS_0xb80d May Alex Frewt 32.0 Developer 28796.82 2378.735000 6 6 21 ... Poor False False False True True False False False True
98285 CUS_0xb80d June Alex Frewt 32.0 Developer 28796.82 2378.735000 6 6 21 ... Standard False False False True True False False False True
98286 CUS_0xb80d July NaN 32.0 Developer 28796.82 2378.735000 6 6 21 ... Poor False False False True True False False False True
98287 CUS_0xb80d August Alex Frewt 32.0 Developer 28796.82 NaN 6 6 21 ... Poor False False False True True False False False True
98300 CUS_0x9d41 May Rothackerz 38.0 Lawyer 41015.55 3152.962500 1194 4 4 ... Standard False False False False True False False False False

63835 rows × 35 columns

Code
# export
def extract_num(string):
    return int(re.sub('[^0-9,]', "", string))

def to_months(Yr_mon):
    try:
        return sum([extract_num(s)*12 if 'Year' in s else extract_num(s) for s in Yr_mon.split('and')])
    except:
        return np.nan
Code
df['Credit_History_Age']=df.Credit_History_Age.apply(to_months)
Code
# export
def clean_pay_behaviour(string):
    try:
        return re.sub('[^a-zA-Z_]', "", string)
    except:
        return np.nan
Code
df.Payment_Behaviour=df.Payment_Behaviour.apply(clean_pay_behaviour)
Code
df.Month=df.Month.apply(lambda s: datetime.strptime(s, '%B').month)
Code
df.Occupation=df.Occupation.replace('_______',np.nan)
df.Credit_Mix=df.Credit_Mix.replace('_',np.nan)
Code
f = lambda x: x.median() if np.issubdtype(x.dtype, np.number) else next(iter(x.mode()), np.nan) 
# df = df.fillna(df.groupby('make').transform(f))
Code
df=df.fillna(df.groupby('Customer_ID').transform(f))
Code
df.to_csv('clean_dataset.csv')
Code
import nbdev; nbdev.nbdev_export()