Skip to content

Personal loans are a lucrative revenue stream for banks. The typical interest rate of a two-year loan in the United Kingdom is around 10%. This might not sound like a lot, but in September 2022 alone UK consumers borrowed around £1.5 billion, which would mean approximately £300 million in interest generated by banks over two years!

You have been asked to work with a bank to clean the data they collected as part of a recent marketing campaign, which aimed to get customers to take out a personal loan. They plan to conduct more marketing campaigns going forward so would like you to ensure it conforms to the specific structure and data types that they specify so that they can then use the cleaned data you provide to set up a PostgreSQL database, which will store this campaign's data and allow data from future campaigns to be easily imported.

They have supplied you with a csv file called "bank_marketing.csv", which you will need to clean, reformat, and split the data, saving three final csv files. Specifically, the three files should have the names and contents as outlined below:

client.csv

columndata typedescriptioncleaning requirements
client_idintegerClient IDN/A
ageintegerClient's age in yearsN/A
jobobjectClient's type of jobChange "." to "_"
maritalobjectClient's marital statusN/A
educationobjectClient's level of educationChange "." to "_" and "unknown" to np.NaN
credit_defaultboolWhether the client's credit is in defaultConvert to boolean data type
mortgageboolWhether the client has an existing mortgage (housing loan)Convert to boolean data type

campaign.csv

columndata typedescriptioncleaning requirements
client_idintegerClient IDN/A
number_contactsintegerNumber of contact attempts to the client in the current campaignN/A
contact_durationintegerLast contact duration in secondsN/A
previous_campaign_contactsintegerNumber of contact attempts to the client in the previous campaignN/A
previous_outcomeboolOutcome of the previous campaignConvert to boolean data type
campaign_outcomeboolOutcome of the current campaignConvert to boolean data type
last_contact_datedatetimeLast date the client was contactedCreate from a combination of day, month, and a newly created year column (which should have a value of 2022);
Format = "YYYY-MM-DD"

economics.csv

columndata typedescriptioncleaning requirements
client_idintegerClient IDN/A
cons_price_idxfloatConsumer price index (monthly indicator)N/A
euribor_three_monthsfloatEuro Interbank Offered Rate (euribor) three-month rate (daily indicator)N/A
import pandas as pd
import numpy as np

# Start coding here...


# CLIENT DATAFRAME
# colum for clients
columns = ['client_id', 'age', 'job', 'marital', 'education', 'credit_default', 'mortgage']

client = pd.read_csv('bank_marketing.csv', 
                     usecols=columns, 
                     index_col=None)

# print(client.info())
# print(dataframe.isna().sum())

# check the value inside the credit columns
# check = client['credit_default'].value_counts()

# # drop unknown value inside credit_default and mortgage column
# client = client[client['credit_default']!= 'unknown']

# client = client[client['mortgage']!= 'unknown']

# data type for each column
# print(client.dtypes)

# Mengubah nilai 'yes' dan 'no' menjadi boolean True dan False pada kolom 'credit_default' dan 'mortgage'
client['credit_default'] = client['credit_default'].replace({'yes': True, 'no': False, 'unknown': np.NaN})
client['mortgage'] = client['mortgage'].replace({'yes': True, 'no': False,'unknown': np.NaN})

# replace data type into boolean
client['credit_default'] = client['credit_default'].astype(bool)
client['mortgage'] = client['mortgage'].astype(bool)

# replace values in job column
client['job'] = client['job'].replace({'admin.': 'admin', 'blue-collar': 'blue_collar', 'self-employed': 'self_employed'})

# replace values in education column and unknown job into np.nan
client['education'] = client['education'].replace({'university.degree.': 'university_degree', 
                                                   'high.school': 'high_school', 
                                                   'professional.course': 'professional_course',
                                                 'basic.9y': 'basic_9y',
                                                 'basic.4y':'basic_4y',
                                                 'basic.6y':'basic_6y',
                                                  'unknown': np.NaN})

# save data into client.csv
print(client.to_csv('client.csv', index=False))



# CAMPAIGN DATAFRAME
# colum to be included
camp_col = ['client_id','number_contacts', 'contact_duration', 'previous_campaign_contacts', 'previous_outcome', 'campaign_outcome', 'month', 'day']

campaign = pd.read_csv('bank_marketing.csv', usecols=camp_col, index_col=None)

# change the object values into boolean valus
campaign['previous_outcome'] = campaign['previous_outcome'].replace({'success': True, 'failure': False, 'nonexistent': np.NaN})
campaign['campaign_outcome'] = campaign['campaign_outcome'].replace({'yes': True, 'no': False})

# replace data type into boolean
campaign['previous_outcome'] = campaign['previous_outcome'].astype(bool)
campaign['previous_outcome'] = campaign['previous_outcome'].astype(bool)

# create new year colum
campaign['year'] = 2022

# replace month column into the right format:
campaign['month'] = campaign['month'].replace ({'may':5,
                                                'jun':6,
                                                'jul':7,
                                                'aug':8,
                                                'oct':10,
                                                'nov':11,
                                                'dec':12,
                                                'mar':3,
                                                'apr':4,
                                                'sep':9})
# Menggunakan pandas untuk mengonversi kolom 'day', 'month', dan 'year' ke dalam kolom bertipe datetime
campaign['last_contact_date'] = pd.to_datetime(campaign[['year', 'month', 'day']])

# Memformat kolom baru menjadi format "YYYY-MM-DD"
campaign['last_contact_date'] = campaign['last_contact_date'].dt.strftime('%Y-%m-%d')

# Mengonversi kolom 'last_contact_date' menjadi tipe data datetime
campaign['last_contact_date'] = pd.to_datetime(campaign['last_contact_date'])

# Menghapus kolom 'year', 'month', dan 'day' dari DataFrame
campaign.drop(['year', 'month', 'day'], axis=1, inplace=True)

# save dataframe into campaign.csv
print(campaign.to_csv('campaign.csv', index=False))


# ECONOMICS DATAFRAME

# column to be included
eco_col = ['client_id', 'cons_price_idx', 'euribor_three_months']

economics = pd.read_csv('bank_marketing.csv', 
                        usecols=eco_col,
                       index_col=None)

# checking the csv file
# print(economics.info())

# save into economics.csv
print(economics.to_csv('economics.csv', index=False))