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 |
imports
import pandas as pd
import numpy as np
# Start coding here...df = pd.read_csv("bank_marketing.csv")Cleaning String Columns
df['job'] = df['job'].str.replace('.','_')
df['education'] = df['education'].str.replace('.','_')
df['education'] = df['education'].replace('unknown', np.nan)Cleaning Boolean Columns
# --- Step 2: Clean the Boolean Columns (Corrected using .map()) ---
print("Converting boolean columns to 1s and 0s using .map()...")
# Create maps for each column
credit_map = {'yes': 1, 'no': 0, 'unknown': 0}
mortgage_map = {'yes': 1, 'no': 0, 'unknown': 0}
prev_outcome_map = {'success': 1, 'failure': 0, 'nonexistent': 0}
campaign_outcome_map = {'yes': 1, 'no': 0}
# Apply the maps
df['credit_default'] = df['credit_default'].map(credit_map)
df['mortgage'] = df['mortgage'].map(mortgage_map)
df['previous_outcome'] = df['previous_outcome'].map(prev_outcome_map)
df['campaign_outcome'] = df['campaign_outcome'].map(campaign_outcome_map)
# --- (Optional but good practice) Convert the data type to boolean ---
print("Changing the data type to boolean...")
boolean_columns = ['credit_default', 'mortgage', 'previous_outcome', 'campaign_outcome']
for col in boolean_columns:
df[col] = df[col].astype(bool)
# You can check the result with
print("\n--- Value counts for previous_outcome after mapping ---")
print(df['previous_outcome'].value_counts())Add Date Column
df['year'] = 2022
month_map = {
'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12
}
# Convert the 'month' column from names to numbers
df['month'] = df['month'].str.lower().map(month_map)
df['last_contact_date'] = pd.to_datetime(df[['year', 'month', 'day']])
df.drop(columns=['year', 'month', 'day'], inplace=True)Split the DataFrame and Save the Final CSV File
print("Splitting the DataFrame and saving the final files...")
# Define columns for client.csv
client_columns = ['client_id', 'age', 'job', 'marital', 'education', 'credit_default', 'mortgage']
client_df = df[client_columns]
client_df.to_csv('client.csv', index=False)# Define columns for campaign.csv
campaign_columns = ['client_id', 'number_contacts', 'contact_duration', 'previous_campaign_contacts', 'previous_outcome', 'campaign_outcome', 'last_contact_date']
campaign_df = df[campaign_columns]
campaign_df.to_csv('campaign.csv', index=False)# Define columns for economics.csv
economics_columns = ['client_id', 'cons_price_idx', 'euribor_three_months']
economics_df = df[economics_columns]
economics_df.to_csv('economics.csv', index=False)
print("\nProject complete! The three files (client.csv, campaign.csv, economics.csv) have been created successfully.")
for col in ["credit_default", "mortgage", "previous_outcome", "campaign_outcome"]:
print(col)
print("--------------")
print(df[col].value_counts())