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
client.csv
column | data type | description | cleaning requirements |
---|---|---|---|
client_id | integer | Client ID | N/A |
age | integer | Client's age in years | N/A |
job | object | Client's type of job | Change "." to "_" |
marital | object | Client's marital status | N/A |
education | object | Client's level of education | Change "." to "_" and "unknown" to np.NaN |
credit_default | bool | Whether the client's credit is in default | Convert to boolean data type |
mortgage | bool | Whether the client has an existing mortgage (housing loan) | Convert to boolean data type |
campaign.csv
campaign.csv
column | data type | description | cleaning requirements |
---|---|---|---|
client_id | integer | Client ID | N/A |
number_contacts | integer | Number of contact attempts to the client in the current campaign | N/A |
contact_duration | integer | Last contact duration in seconds | N/A |
previous_campaign_contacts | integer | Number of contact attempts to the client in the previous campaign | N/A |
previous_outcome | bool | Outcome of the previous campaign | Convert to boolean data type |
campaign_outcome | bool | Outcome of the current campaign | Convert to boolean data type |
last_contact_date | datetime | 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" |
economics.csv
economics.csv
column | data type | description | cleaning requirements |
---|---|---|---|
client_id | integer | Client ID | N/A |
cons_price_idx | float | Consumer price index (monthly indicator) | N/A |
euribor_three_months | float | Euro Interbank Offered Rate (euribor) three-month rate (daily indicator) | N/A |
import pandas as pd
import numpy as np
# Import the data from bank_marketing.csv
bank_marketing = pd.read_csv('bank_marketing.csv')
# load the first 5 rows to visually inspect the data set
bank_marketing.head()
# checking the number of rows of the entire data set
bank_marketing.shape
# Extract the columns names contained in the data set
bank_marketing.columns
# Check the column datatypes
bank_marketing.dtypes
# start subsetting the columns for each dataframe by selecting the required columns
# select the columns required in the client dataframe
client_columns = ['client_id', 'age', 'job', 'marital', 'education', 'credit_default','mortgage']
# Generate the client dataframe
client = bank_marketing[client_columns]
# load the first 5 rows of the client dataframe
client.head()
# select the columns required in the campaign dataframe
campaign_columns = ['client_id', 'number_contacts', 'contact_duration', 'previous_campaign_contacts', 'previous_outcome', 'campaign_outcome','month', 'day']
# Generate the campaign dataframe
campaign = bank_marketing[campaign_columns]
# change "day" column datatype from int to str
campaign['day'] = campaign['day'].astype(str)
# change "month" column datatype from object to str
campaign['month'] = campaign['month'].astype(str)
# When converting to strings, ensure leading zeros for single-digit months and days for consistent date formatting
campaign['month'] = campaign['month'].apply(lambda x: x.zfill(2))
campaign['day'] = campaign['day'].apply(lambda x: x.zfill(2))
# create "last_contact_date" column from the "month" and "day" columns
campaign["last_contact_date"] = campaign['month'].apply(lambda x : x.capitalize()) + "-" + campaign['day']
# add a year value e.g. 2022 so that pd.to_datetime() can be able to convert the date
campaign["last_contact_date"] = pd.to_datetime("2022-" + campaign['month'] + "-" + campaign['day'], errors='coerce', format='%Y-%b-%d')
# drop the 'month' and the 'day' columns since we no longer need them
campaign.drop(columns=['month','day'],inplace=True)
# load the first 5 rows of the campaign dataframe
campaign.head()
# select the columns required in the campaign dataframe
economics_columns = ['client_id','cons_price_idx','euribor_three_months']
# Generate the economics dataframe
economics = bank_marketing[economics_columns]
# view the first 5 rows of the economics dataframe
economics.head()
2. Cleaning the data
client['education'] = client['education'].replace(['.','unknown'],\
['-',np.NaN])
client.head()
# Check the education columns values after performing the replacement of
# values above
client['education'].unique()
# check the values in 'job' column
client['job'].unique()
# replace the '.' periods in the 'job columns'
client['job'] = client['job'].replace(['.',''])