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 and store 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 set up a PostgreSQL database to store this campaign's data, designing the schema in a way that would 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, in order to save separate files based on the tables you will create. It is recommended to use pandas
for these tasks.
Lastly, you will write the SQL code that the bank can execute to create the tables and populate with the data from the csv files. As the bank are quite strict about their security, you'll provide the database design script as a .sql
file that they can then run.
You have been asked to design a database that will have three tables:
client
column | data type | description |
---|---|---|
id | serial | Client ID - primary key |
age | integer | Client's age in years |
job | text | Client's type of job |
marital | text | Client's marital status |
education | text | Client's level of education |
credit_default | boolean | Whether the client's credit is in default |
housing | boolean | Whether the client has an existing housing loan (mortgage) |
loan | boolean | Whether the client has an existing personal loan |
campaign
column | data type | description |
---|---|---|
campaign_id | serial | Campaign ID - primary key |
client_id | serial | Client ID - references id in the client table |
number_contacts | integer | Number of contact attempts to the client in the current campaign |
contact_duration | integer | Last contact duration in seconds |
pdays | integer | Number of days since contact in previous campaign (999 = not previously contacted) |
previous_campaign_contacts | integer | Number of contact attempts to the client in the previous campaign |
previous_outcome | boolean | Outcome of the previous campaign |
campaign_outcome | boolean | Outcome of the current campaign |
last_contact_date | date | Last date the client was contacted |
economics
column | data type | description |
---|---|---|
client_id | serial | Client ID - references id in the client table |
emp_var_rate | float | Employment variation rate (quarterly indicator) |
cons_price_idx | float | Consumer price index (monthly indicator) |
euribor_three_months | float | Euro Interbank Offered Rate (euribor) three month rate (daily indicator) |
number_employed | float | Number of employees (quarterly indicator) |
#Load our packages
import pandas as pd
import numpy as np
#Reading in our csv file into a dataframe
df = pd.read_csv('bank_marketing.csv')
print(df.head())
df.info()
#Using column indexing to create the dataframes instead of typing out all the columns names.
index_client = [0,1,2,3,4,5,6,7]
index_campaign = [0,12,11,13,14,15,21,9,10]
index_economics = [0,16,17,19,20]
#Dataframes created.
df_client = df.iloc[:,index_client]
df_campaign = df.iloc[:,index_campaign]
df_economics = df.iloc[:,index_economics]
#Examining the new dataframes.
df_client.info()
df_client.head()
df_campaign.info()
df_campaign.head()
df_economics.info()
df_economics.head()
#Creating the the date column, I already thought to do this before I read the instrucitons to do so.
print(df_campaign.head(5))
df_campaign['last_contact_date'] = '2022'+'-'+df_campaign['month'].str.capitalize()+'-'+df_campaign['day'].astype(str)
df_campaign['last_contact_date'] = pd.to_datetime(df_campaign['last_contact_date'], format='%Y-%b-%d', errors = 'coerce')
print(df_campaign.head(5))
#Dropping the old date part columns
df_campaign = df_campaign.drop(['month','day'], axis = 1)
df_campaign.info()
print(df_campaign.head())
#Renaming columns
df_client.info()
client_mapping = {'client_id':'id'}
df_client = df_client.rename(columns=client_mapping)
df_client.info()
#Renaming columns
campaing_mapping ={'duration': 'contact_duration', 'y': 'campaign_outcome', 'campaign': 'number_contacts','previous': 'previous_campaign_contacts','poutcome': 'previous_outcome'}
df_campaign = df_campaign.rename(columns=campaing_mapping)
df_campaign.info()
#Renaming columns
economics_mapping ={"euribor3m":"euribor_three_months", "nr_employed": "number_employed"}
df_economics= df_economics.rename(columns=economics_mapping)
df_economics.info()
#Replacing the . for _ and unknow for Nan.
df_client['education'] = df_client['education'].str.replace('.','_')
df_client['education'] = df_client['education'].replace('unknown', np.NaN)
#Cleaning some values and replacing others.
df_client['job'] = df_client['job'].replace('.','')
df_campaign['previous_outcome'] = df_campaign['previous_outcome'].replace('nonexistent', np.NaN)
df_campaign['previous_outcome'] = df_campaign['previous_outcome'].map({'success':1,'failure':0})
df_campaign['campaign_outcome'].map({'success':1,'failure':0})
#Adding in the static value column.
df_campaign['campaign_id'] = 1
#Checking to see if our cleaning worked.
print(df_client.head())
print(df_campaign.head())
print(df_economics.head())
#Turning the dataframes into csv files.
df_client.to_csv('client.csv', index = False)
df_campaign.to_csv('campaign.csv', index = False)
df_economics.to_csv('economics.csv', index = False)
#Creating and loading the csv files.
client_table = """CREATE TABLE client
(
id SERIAL PRIMARY KEY,
age INTEGER,
job TEXT,
marital TEXT,
education TEXT,
credit_default BOOLEAN,
housing BOOLEAN,
loan BOOLEAN
);
\copy client from 'client.csv' DELIMITER ',' CSV HEADER
"""
campaign_table = """CREATE TABLE campaign
(
campaign_id SERIAL PRIMARY KEY,
client_id SERIAL references client (id),
number_contacts INTEGER,
contact_duration INTEGER,
pdays INTEGER,
previous_campaign_contacts INTEGER,
previous_outcome BOOLEAN,
campaign_outcome BOOLEAN,
last_contact_date DATE
);
\copy campaign from 'campaign.csv' DELIMITER ',' CSV HEADER
"""
economics_table = """CREATE TABLE economics
(
client_id SERIAL references client (id),
emp_var_rate FLOAT,
cons_price_idx FLOAT,
euribor_three_months FLOAT,
number_employed FLOAT
);
\copy economics from 'economics.csv' DELIMITER ',' CSV HEADER
"""