Skip to content

Cleaning Bank Marketing Campaign Data

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

columndata typedescriptioncleaning requirements
client_idintegerClient IDN/A
ageintegerClient's age in yearsN/A
jobobjectClient's type of jobChange "." to "_"
maritalobjectClient's marital statusN/A
educationobjectClient's level of educationChange "." to "_" and "unknown" to np.NaN
credit_defaultboolWhether the client's credit is in defaultConvert to boolean data type:
1 if "yes", otherwise 0
mortgageboolWhether the client has an existing mortgage (housing loan)Convert to boolean data type:
1 if "yes", otherwise 0

campaign.csv

columndata typedescriptioncleaning requirements
client_idintegerClient IDN/A
number_contactsintegerNumber of contact attempts to the client in the current campaignN/A
contact_durationintegerLast contact duration in secondsN/A
previous_campaign_contactsintegerNumber of contact attempts to the client in the previous campaignN/A
previous_outcomeboolOutcome of the previous campaignConvert to boolean data type:
1 if "success", otherwise 0.
campaign_outcomeboolOutcome of the current campaignConvert to boolean data type:
1 if "yes", otherwise 0.
last_contact_datedatetimeLast date the client was contactedCreate 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

columndata typedescriptioncleaning requirements
client_idintegerClient IDN/A
cons_price_idxfloatConsumer price index (monthly indicator)N/A
euribor_three_monthsfloatEuro Interbank Offered Rate (euribor) three-month rate (daily indicator)N/A

Load data

# Import libraries
import pandas as pd
import numpy as np

# Load csv file
bank_marketing = pd.read_csv("bank_marketing.csv")

# Check value counts and data types
for col in ["credit_default", "mortgage", "previous_outcome", "campaign_outcome"]:
    print(col)
    print("--------------")
    print(df[col].value_counts(), '\n')

print(bank_marketing.info())

Clean data

Client

# Replace '.' to '_'
bank_marketing['job_formatted'] = bank_marketing['job'].str.replace('.', '_')

# Replace '.' to '_' and 'unknown' to np.NaN
bank_marketing['education_formatted'] = bank_marketing['education'].str.replace('.', '_')
bank_marketing['education_formatted'] = bank_marketing['education_formatted'].replace('unknown', np.NaN)

# Convert to boolean data type by using a function
def convert_to_boolean(value):
    mapping = {
        'yes': True,
        'unknown': False,
        'no': False
    }
    return mapping.get(value, None)
    
bank_marketing['credit_default_formatted'] = bank_marketing['credit_default'].apply(convert_to_boolean)
bank_marketing['mortgage_formatted'] = bank_marketing['mortgage'].apply(convert_to_boolean)

Campaign

from datetime import datetime

# Convert to boolean data type by using a function
def convert_to_boolean_2(value):
    mapping = {
        'nonexistent': False,
        'failure': False,
        'success': True
    }
    return mapping.get(value, None)

bank_marketing['campaign_outcome_formatted'] = bank_marketing['campaign_outcome'].apply(convert_to_boolean)
bank_marketing['previous_outcome_formatted'] = bank_marketing['previous_outcome'].apply(convert_to_boolean_2)

# Concatenate day, month and 2022 and create a YYYY-MM-DD format from a bbDDYYY format
bank_marketing['last_contact_date'] = bank_marketing['month'].astype(str) + bank_marketing['day'].astype(str) + '2022'

bank_marketing['last_contact_date'] = pd.to_datetime(bank_marketing['last_contact_date'], format='%b%d%Y')
bank_marketing['last_contact_date'] = bank_marketing['last_contact_date'].dt.strftime('%Y-%m-%d')

Store data

Client

# Add all the columns
client = bank_marketing[['client_id', 'age', 'job_formatted', 'marital', 'education_formatted', 'credit_default_formatted', 'mortgage_formatted']]
# Rename the columns
client.rename(columns={'job_formatted': 'job', 'education_formatted': 'education', 'credit_default_formatted': 'credit_default', 'mortgage_formatted': 'mortgage'}, inplace=True)
# Store to csv
print(client.head())
client.to_csv('client.csv', index=False)

Campaign

# Add all the columns
campaign = bank_marketing[['client_id', 'number_contacts', 'contact_duration', 'previous_campaign_contacts', 'previous_outcome_formatted', 'campaign_outcome_formatted', 'last_contact_date']]
# Rename the columns
campaign.rename(columns={'previous_outcome_formatted': 'previous_outcome', 'campaign_outcome_formatted': 'campaign_outcome'}, inplace=True)
print(campaign.head())
# Store to csv
campaign.to_csv('campaign.csv', index=False)

Economics