Skip to content
Clean and store data
  • AI Chat
  • Code
  • Report

  • 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 and store 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 set up a PostgreSQL database to store this campaign's data, designing the schema in a way that would 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, in order to save separate files based on the tables you will create. It is recommended to use pandas for these tasks.

    Lastly, you will write the SQL code that the bank can execute to create the tables and populate with the data from the csv files. As the bank are quite strict about their security, you'll save SQL files as multiline string variables that they can then use to create the database on their end.

    You have been asked to design a database that will have three tables:

    client

    columndata typedescriptionoriginal column in dataset
    idserialClient ID - primary keyclient_id
    ageintegerClient's age in yearsage
    jobtextClient's type of jobjob
    maritaltextClient's marital statusmarital
    educationtextClient's level of educationeducation
    credit_defaultbooleanWhether the client's credit is in defaultcredit_default
    housingbooleanWhether the client has an existing housing loan (mortgage)housing
    loanbooleanWhether the client has an existing personal loanloan

    campaign

    columndata typedescriptionoriginal column in dataset
    campaign_idserialCampaign ID - primary keyN/A - new column
    client_idserialClient ID - references id in the client tableclient_id
    number_contactsintegerNumber of contact attempts to the client in the current campaigncampaign
    contact_durationintegerLast contact duration in secondsduration
    pdaysintegerNumber of days since contact in previous campaign (999 = not previously contacted)pdays
    previous_campaign_contactsintegerNumber of contact attempts to the client in the previous campaignprevious
    previous_outcomebooleanOutcome of the previous campaignpoutcome
    campaign_outcomebooleanOutcome of the current campaigny
    last_contact_datedateLast date the client was contactedA combination of day, month, and the newly created year

    economics

    columndata typedescriptionoriginal column in dataset
    client_idserialClient ID - references id in the client tableclient_id
    emp_var_ratefloatEmployment variation rate (quarterly indicator)emp_var_rate
    cons_price_idxfloatConsumer price index (monthly indicator)cons_price_idx
    euribor_three_monthsfloatEuro Interbank Offered Rate (euribor) three month rate (daily indicator)euribor3m
    number_employedfloatNumber of employees (quarterly indicator)nr_employed
    import pandas as pd
    import numpy as np
    
    # Import file
    df_bank = pd.read_csv("bank_marketing.csv")
    # Read first 5 lines
    print(df_bank.head())
    # Sunset bank dataframe to get client data
    client_columns = ['client_id', 'age', 'job', 'marital', 'education', 'credit_default', 'housing', 'loan']
    df_client = df_bank[client_columns]
    print(df_client.head())
    df_client.info()
    df_clients = df_client.rename(columns={"client_id": "id"})
    print(df_clients.head())
    # Rename "education" column values
    df_clients["education"] = df_clients["education"].str.replace('.', '_')
    df_clients["education"] = df_clients["education"].str.replace('unknown', '')
    df_clients['job'] = df_clients['job'].str.replace(".", "")
    print(df_clients.info())
    # Export dataframe to csv
    df_clients.to_csv("client.csv", index=False)
    print(f"Le DataFrame a été exporté en {df_clients}")
    print(df_bank.columns)
    # Sunset bank dataframe to get compaign data
    campaign_columns = ['client_id', 'campaign', 'duration', 'pdays', 'previous', 'poutcome', 'y']
    df_campaign = df_bank[campaign_columns]
    
    # Create new column with value 1
    df_campaign['campaign_id'] = 1
    # Rename columns
    rename_columns = {
        "campaign": "number_contacts",
        "duration": "contact_duration",
        "previous": "previous_campaign_contact",
        "poutcome": "previous_outcome",
        "y": "campaign_outcome"
    }
    df_campaign = df_campaign.rename(columns=rename_columns)
    # Convert the column to date format
    df_campaign['last_contact_date'] = pd.to_datetime('2022-' + df_bank['month'].astype(str) + '-' + df_bank['day'].astype(str))
    # print dataframe information
    print(df_campaign.head())
    print(df_campaign.info())
    # Convert columns to fit the description of the dataset
    df_campaign['previous_outcome'] = df_campaign['previous_outcome'].map({'success': 1, 'failure': 0, 'nonexistent': np.nan})
    df_campaign['campaign_outcome'] = df_campaign['campaign_outcome'].map({'success': 1, 'failure': 0})
    
    # Print dataframe information
    df_campaign.info()
    # Exoport dataframe to csv format
    df_campaign.to_csv("campaign.csv", index=False)
    # Sunset bank dataframe to get economic data
    economic_columns = ['client_id', 'emp_var_rate', 'cons_price_idx', 'euribor3m', 'nr_employed']
    df_economic = df_bank[economic_columns]
    df_economic.head()
    # Rename columns
    economic_rename = {"euribor3m": "euribor_three_months", "nr_employed": "number_employed"}
    df_economic = df_economic.rename(columns=economic_rename)
    df_economic.head()
    # Export file to csv
    df_economic.to_csv("economics.csv", index=False)