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:1 if "yes", otherwise 0 |
mortgage | bool | Whether the client has an existing mortgage (housing loan) | Convert to boolean data type:1 if "yes", otherwise 0 |
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:1 if "success", otherwise 0. |
campaign_outcome | bool | Outcome of the current campaign | Convert to boolean data type:1 if "yes", otherwise 0. |
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
# Read in csv
bank_marketing = pd.read_csv("bank_marketing.csv")
# Split into the three tables by subsetting
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"]]df = pd.read_csv("bank_marketing.csv")
for col in ["credit_default", "mortgage", "previous_outcome", "campaign_outcome"]:
print(col)
print("--------------")
print(df[col].value_counts())#1. Replacing the strings '.' with '_' & 'unknown' with 'np.NaN' in the Job and education column respectively
client['job'] = client['job'].str.replace(".", "_")
client["education"] = client["education"].str.replace(".", "_")
client['education'] = client['education'].replace("unknown", np.NaN)
#2. Converting the credit and mortgage columns to boolean, using a for loop and pandas .map function to replace the default values to 1/0
for column in ['credit_default', 'mortgage']:
client[column] = client[column].map({
"yes": 1,
"no": 0,
"unknown": 0
})
client[column] = client[column].astype(bool)
#checking the datatype and printing the head of the table
print(client.dtypes)
print(client.head())#3. Converting the "previous_outcome", "campaign_outcome" columns to boolean and using pandas .map function to replace the default values to 1/0
#Converting individual columns but a for loop can also be used by passing all parameters
campaign["previous_outcome"] = campaign["previous_outcome"].map({
"success": 1,
"nonexistent": 0,
"failure": 0,
})
campaign["campaign_outcome"] = campaign["campaign_outcome"].map({
"yes": 1,
"no": 0
})
#changing the DTypes from float and int to boolean respectively
for column in ["campaign_outcome", "previous_outcome"]:
campaign[column] = campaign[column].astype(bool)#4. Working on the last_contact_date column
#Adding the year column as stated
campaign['year'] = "2022"
#changing the "day" dtype from int to str
campaign["day"] = campaign["day"].astype("str")
#combining the day, month and year into the newly created last_contact_date
campaign["last_contact_date"] = campaign["year"]+ "-" + campaign["month"]+ "-" + campaign["day"]
#changing the format to datetime instead of object and using the format YYYY-MM-DD
campaign["last_contact_date"] = pd.to_datetime(campaign["last_contact_date"])
#dropping extra columns as stated in the question
campaign.drop(columns=['year', 'day', 'month'], inplace=True)
#checking the datatype and printing the head of the table
print(campaign.dtypes)
print(campaign.head())client.to_csv('client.csv', index=False)
campaign.to_csv('campaign.csv', index=False)
economics.to_csv('economics.csv', index=False)