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:
1 if "yes", otherwise 0
mortgageboolWhether the client has an existing mortgage (housing loan)Convert to boolean data type:
1 if "yes", otherwise 0

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:
1 if "success", otherwise 0.
campaign_outcomeboolOutcome of the current campaignConvert to boolean data type:
1 if "yes", otherwise 0.
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...
file = "bank_marketing.csv"
bank_marketing_df = pd.read_csv(file)
bank_marketing_df.head(5)
# Check the data types
bank_marketing_df.info()
# Task desc: Change(job col) "." to "_"
bank_marketing_df['job'] = bank_marketing_df['job'].str.replace('.', '_')

# Task desc: Change(education col) "." to "_" and "unknown" to np.NaN
bank_marketing_df['education'] = bank_marketing_df['education'].str.replace('.', '_')
bank_marketing_df.loc[bank_marketing_df['education'] == 'unknown', 'education' ] = np.NaN

# Task desc: Convert(credit_default) to boolean data type
bank_marketing_df['credit_default'] = bank_marketing_df['credit_default'].map({'yes': 1, 'no': 0, 'unknown': 0})
bank_marketing_df['credit_default'] = bank_marketing_df['credit_default'].astype('bool')

# Task desc: Convert(mortgage) to boolean data type
bank_marketing_df['mortgage'] = bank_marketing_df['mortgage'].map({'yes': 1, 'no': 0, 'unknown': 0})
bank_marketing_df['mortgage'] = bank_marketing_df['mortgage'].astype('bool')

# Task desc: Convert(previous_outcome) to boolean data type
bank_marketing_df['previous_outcome'] = bank_marketing_df['previous_outcome'].map({"success": 1, "failure": 0, "nonexistent": 0})
bank_marketing_df['previous_outcome'] = bank_marketing_df['previous_outcome'].astype('bool')

# Task desc: Convert(campaign_outcome) to boolean data 
bank_marketing_df['campaign_outcome'] = bank_marketing_df['campaign_outcome'].map({'yes': 1, 'no': 0, 'unknown': 0})
bank_marketing_df['campaign_outcome'] = bank_marketing_df['campaign_outcome'].astype('bool')

# Create from a combination of day, month, and a newly created year column (which should have a value of 2022); Format = "YYYY-MM-DD"

# Task desc: create a new column 'year' with constant value 2022
bank_marketing_df['year'] = 2022
# map months(str) to their appropriate integer values
# first make sure the month values are in consistent string format
bank_marketing_df['month'] = bank_marketing_df['month'].str.lower()
month_map = {
    'january': 1, 'february': 2, 'march': 3, 'april': 4,
    'may': 5, 'june': 6, 'july': 7, 'august': 8,
    'september': 9, 'october': 10, 'november': 11, 'december': 12
}

# Convert the month column to numeric values
bank_marketing_df['month'] = bank_marketing_df['month'].map(month_map)

# Create a datetime column by combining 'year', 'month', and 'day'
bank_marketing_df['last_contact_date'] = pd.to_datetime(bank_marketing_df[['year', 'month', 'day']], format='%Y-%m-%d')
# Check if data types are corrected
bank_marketing_df.head(5)
# Check if data types are corrected
bank_marketing_df.info()
# create the client columns subset
client = bank_marketing_df[['client_id', 'age', 'job',  'marital', 'education', 'credit_default', 'mortgage' ]]

# create the campaign columns subset
campaign = bank_marketing_df[['client_id', 'contact_duration', 'number_contacts', 'previous_campaign_contacts', 'previous_outcome', 'campaign_outcome', 'last_contact_date' ]]

# create the economics columns subset
economics = bank_marketing_df[['client_id', 'cons_price_idx', 'euribor_three_months' ]]

# Save DataFrames to CSV files without an index
client.to_csv('client.csv', index=False)
campaign.to_csv('campaign.csv', index=False)
economics.to_csv('economics.csv', index=False)