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"tonp.NaN | 
| credit_default | bool | Whether the client's credit is in default | Convert to booleandata type:1if"yes", otherwise0 | 
| mortgage | bool | Whether the client has an existing mortgage (housing loan) | Convert to boolean data type: 1if"yes", otherwise0 | 
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: 1if"success", otherwise0. | 
| campaign_outcome | bool | Outcome of the current campaign | Convert to boolean data type: 1if"yes", otherwise0. | 
| last_contact_date | datetime | Last date the client was contacted | Create from a combination of day,month, and a newly createdyearcolumn (which should have a value of2022);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
bank_marketing = pd.read_csv("bank_marketing.csv")
df = bank_marketing.copy()
df["year"] = "2022"
df["day"] = df["day"].astype('str')
df["month"] = df["month"].str.capitalize()
df["last_contact_date"] = df["year"] + "-"+ df["month"]+"-" + df["day"]
df["last_contact_date"] = pd.to_datetime(df["last_contact_date"], infer_datetime_format =True)
#Seperate the columns of interest, saving as new dataframe, client 
client = df[["client_id", "job", "age", "marital", "education", "credit_default", "mortgage"]]
#Clean up object data
client["education"] = client["education"].str.replace(".", "_")
client["job"] = client["job"].str.replace(".", "_")
client["education"] = client["education"].replace("unknown", np.NaN)
#Use .loc to set values to a 0 or 1 which can convert to boolean, once changed to integer
client.loc[client["credit_default"].isin(["yes"]), "credit_default"] = "1"
client.loc[client["credit_default"].isin(["no", "unknown"]), "credit_default"] = "0"
client["credit_default"] = client["credit_default"].astype('int32').astype(bool)
client.loc[client["mortgage"].isin(["yes"]), "mortgage"] = "1"
client.loc[client["mortgage"].isin(["no", "unknown"]), "mortgage"] = "0"
client["mortgage"] = client["mortgage"].astype("int64").astype(bool)
#Create the client file 
client.to_csv('client.csv', index=False) #leaving index in creates unnecessary column
#Seperate columns about the campaign
campaign = df[["client_id", "number_contacts", "contact_duration", "previous_campaign_contacts", "previous_outcome", "campaign_outcome", "last_contact_date"]]
#Set values using .loc, then convert to int and finally bool. Success is true, other is false
campaign.loc[campaign["previous_outcome"].isin(['success']), "previous_outcome"] = 1
campaign.loc[campaign["previous_outcome"].isin(["failure", "nonexistent"]), "previous_outcome"] = 0
campaign["previous_outcome"] = campaign["previous_outcome"].astype('int32').astype(bool)
campaign.loc[campaign["campaign_outcome"].isin(["yes"]), "campaign_outcome"] = 1
campaign.loc[campaign["campaign_outcome"].isin(["no"]), "campaign_outcome"] = 0
campaign["campaign_outcome"] = campaign["campaign_outcome"].astype('int32').astype(bool)
campaign.to_csv('campaign.csv', index=False
               )
#Finally, seperate out the economic index specific columns. Save to file
economics = df[["client_id", "cons_price_idx", "euribor_three_months"]]
economics.to_csv('economics.csv', index=False)
explore_campaign = campaign.copy()
explore_campaign.groupby("previous_outcome")["previous_campaign_contacts"].max()
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())