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...

# Read the Given: [bank_marketing.csv] File.

bank_marketing = pd.read_csv(filepath_or_buffer='bank_marketing.csv', encoding='UTF-8')
bank_marketing.head()
bank_marketing.info()
# Spliting bank_marketing into the three tables
client = bank_marketing[["client_id", "age", "job", "marital", 
                    "education", "credit_default", "mortgage"]]
campaign = bank_marketing[["client_id", "number_contacts", "month", "day", 
               "contact_duration", "previous_campaign_contacts", "previous_outcome", "campaign_outcome"]]
economics = bank_marketing[["client_id", "cons_price_idx", "euribor_three_months"]]

Modifying the client dataset

# Cleaning job Column: Change "." to "_"
client['job'] = client['job'].str.replace('.', '_')
# Cleaning education column: Change "." to "_" and "unknown" to np.NaN

# Client's level of education Change "." to "_"
client['education'] = client['education'].str.replace('.', '_')

# Client's level of education Change "unknown" to np.NaN
client['education'] = client['education'].apply(lambda x: np.NaN if x == 'unknown' else x)
What to do with the unknown values?
  • For credit_default we assume that unknown means no / False. Onus is on the Bank to verify the credit_default
  • For mortgage we assume that unknown means no / False. No known mortgage is there.

This is a marketing data so risk is low. During actual loan underwriting process the credit risk analysis must be performed and actual credit_default and mortgage must be cross checked.

for column in ["credit_default", "mortgage"]:
    client[column] = client[column].map({'no': 0, 'unknown': 0, 'no': 0})
    client[column] = client[column].astype(bool)

Modifying the campaign dataset

campaign["previous_outcome"].unique()
bank_marketing['campaign_outcome'].unique()
# previous_outcome Convert to boolean data type
campaign["previous_outcome"] = campaign["previous_outcome"].map({ "failure": 0,
                                                                 "nonexistent": 0,
                                                                 "success": 1})
campaign["previous_outcome"] = campaign["previous_outcome"].astype(bool)

# campaign_outcome Convert to boolean data type
campaign["campaign_outcome"] = campaign["campaign_outcome"].map({"no": 0, 
                                                                 "yes": 1})
campaign["campaign_outcome"] = campaign["campaign_outcome"].astype(bool)
# last_contact_date [Last date the client was contacted] 	
# Create from a combination of day, month, and a newly created year column 
# (which should have a value of 2022); Format = "YYYY-MM-DD"

# Year Column to be added to campaign dataframe
campaign["year"] = "2022"

# Capitalize month and day columns
campaign["month"] = campaign["month"].str.capitalize()

# Convert day to string
campaign["day"] = campaign["day"].astype(str)

# Create last_contact_date column from above columns
campaign["last_contact_date"] = campaign["year"] + "-" + campaign["month"] + "-" + campaign["day"]

# Converting to datetime
campaign["last_contact_date"] = pd.to_datetime(campaign["last_contact_date"], 
                                               format="%Y-%b-%d")
# Drop the redundant columns
campaign.drop(columns=["month", "day", "year"], inplace=True)