Using One-Hot Encoding to Convert Categorical data to Numerical data

1. Load the data

In [1]:
import pandas as pd
import numpy as np
In [2]:
dataset_1 = pd.read_csv("Banking_Marketing.csv")

2. Drop any NA values

In [3]:
dataset_1=dataset_1.dropna()

3. Exclude the Numerical columns for encoding

In [4]:
dataset_column_category = dataset_1.select_dtypes(exclude=[np.number]).columns

4. Categorical columns after excluding the numerical values

In [5]:
dataset_column_category
Out[5]:
Index(['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact',
       'month', 'day_of_week', 'poutcome'],
      dtype='object')
In [6]:
dataset_1[dataset_column_category].head()
Out[6]:
job marital education default housing loan contact month day_of_week poutcome
0 blue-collar married basic.4y unknown yes no cellular aug thu nonexistent
1 technician married unknown no no no cellular nov fri nonexistent
2 management single university.degree no yes no cellular jun thu success
3 services married high.school no no no cellular apr fri nonexistent
4 retired married basic.4y no yes no cellular aug fri success

5. Here we use Label Encoding technique to simple encode the categorical columns without being concerned about the number of labels that each categorical columns might have. For Example, the column "job" has 12 labels, so the label encoder will be encoding it from 1 to 11. We will divide each labels of the categorical columns into individual columns using the OneHotEncoder

In [7]:
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()

for i in dataset_column_category:
    dataset_1[i] = label_encoder.fit_transform(dataset_1[i])
print("Label Encoded Data: ")
dataset_1.head()
Label Encoded Data: 
Out[7]:
age job marital education default housing loan contact month day_of_week ... campaign pdays previous poutcome emp_var_rate cons_price_idx cons_conf_idx euribor3m nr_employed y
0 44.0 1 1 0 1 2 0 0 1 2 ... 1 999 0 1 1.4 93.444 -36.1 4.963 5228.1 0
1 53.0 9 1 7 0 0 0 0 7 0 ... 1 999 0 1 -0.1 93.200 -42.0 4.021 5195.8 0
2 28.0 4 2 6 0 2 0 0 4 2 ... 3 6 2 2 -1.7 94.055 -39.8 0.729 4991.6 1
3 39.0 7 1 3 0 0 0 0 0 0 ... 2 999 0 1 -1.8 93.075 -47.1 1.405 5099.1 0
4 55.0 5 1 0 0 2 0 0 1 0 ... 1 3 1 2 -2.9 92.201 -31.4 0.869 5076.2 1

5 rows × 21 columns

6. We divide each labels of the categorical columns into individual columns using the OneHotEncoder

In [8]:
from sklearn.preprocessing import OneHotEncoder
one_hot_encoding = OneHotEncoder(sparse=False)
one_hotEncoded = one_hot_encoding.fit_transform(dataset_1[dataset_column_category])
C:\Users\tkhan050\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\preprocessing\_encoders.py:415: FutureWarning: The handling of integer data will change in version 0.22. Currently, the categories are determined based on the range [0, max(values)], while in the future they will be determined based on the unique values.
If you want the future behaviour and silence this warning, you can specify "categories='auto'".
In case you used a LabelEncoder before this OneHotEncoder to convert the categories to integers, then you can now use the OneHotEncoder directly.
  warnings.warn(msg, FutureWarning)
In [9]:
one_hotEncoded
Out[9]:
array([[0., 1., 0., ..., 0., 1., 0.],
       [0., 0., 0., ..., 0., 1., 0.],
       [0., 0., 0., ..., 0., 0., 1.],
       ...,
       [0., 0., 0., ..., 0., 1., 0.],
       [0., 0., 0., ..., 0., 1., 0.],
       [0., 0., 0., ..., 0., 1., 0.]])

7. Creating a new dataframe for the OneHotEncoded columns

In [10]:
new_onehot_encoded_dataFrame = pd.DataFrame(one_hotEncoded,
                                            columns=one_hot_encoding.get_feature_names(dataset_column_category))
In [11]:
new_onehot_encoded_dataFrame.head()
Out[11]:
job_0.0 job_1.0 job_2.0 job_3.0 job_4.0 job_5.0 job_6.0 job_7.0 job_8.0 job_9.0 ... month_8.0 month_9.0 day_of_week_0.0 day_of_week_1.0 day_of_week_2.0 day_of_week_3.0 day_of_week_4.0 poutcome_0.0 poutcome_1.0 poutcome_2.0
0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 ... 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0
2 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0
3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 ... 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0
4 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0

5 rows × 53 columns

8. One-hot Encoded columns

In [12]:
new_onehot_encoded_dataFrame.columns
Out[12]:
Index(['job_0.0', 'job_1.0', 'job_2.0', 'job_3.0', 'job_4.0', 'job_5.0',
       'job_6.0', 'job_7.0', 'job_8.0', 'job_9.0', 'job_10.0', 'job_11.0',
       'marital_0.0', 'marital_1.0', 'marital_2.0', 'marital_3.0',
       'education_0.0', 'education_1.0', 'education_2.0', 'education_3.0',
       'education_4.0', 'education_5.0', 'education_6.0', 'education_7.0',
       'default_0.0', 'default_1.0', 'default_2.0', 'housing_0.0',
       'housing_1.0', 'housing_2.0', 'loan_0.0', 'loan_1.0', 'loan_2.0',
       'contact_0.0', 'contact_1.0', 'month_0.0', 'month_1.0', 'month_2.0',
       'month_3.0', 'month_4.0', 'month_5.0', 'month_6.0', 'month_7.0',
       'month_8.0', 'month_9.0', 'day_of_week_0.0', 'day_of_week_1.0',
       'day_of_week_2.0', 'day_of_week_3.0', 'day_of_week_4.0', 'poutcome_0.0',
       'poutcome_1.0', 'poutcome_2.0'],
      dtype='object')

Dummy encoding

In [13]:
dataset_1 = pd.read_csv("Banking_Marketing.csv")
dataset_1=dataset_1.dropna()
dataset_column_category = dataset_1.select_dtypes(exclude=[np.number]).columns
print(dataset_column_category)
dataset_1[dataset_column_category].head()
Index(['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact',
       'month', 'day_of_week', 'poutcome'],
      dtype='object')
Out[13]:
job marital education default housing loan contact month day_of_week poutcome
0 blue-collar married basic.4y unknown yes no cellular aug thu nonexistent
1 technician married unknown no no no cellular nov fri nonexistent
2 management single university.degree no yes no cellular jun thu success
3 services married high.school no no no cellular apr fri nonexistent
4 retired married basic.4y no yes no cellular aug fri success
In [14]:
onehot_dummyEncoding = pd.get_dummies(dataset_1[dataset_column_category],prefix=dataset_column_category)
In [15]:
onehot_dummyEncoding.columns
Out[15]:
Index(['job_admin.', 'job_blue-collar', 'job_entrepreneur', 'job_housemaid',
       'job_management', 'job_retired', 'job_self-employed', 'job_services',
       'job_student', 'job_technician', 'job_unemployed', 'job_unknown',
       'marital_divorced', 'marital_married', 'marital_single',
       'marital_unknown', 'education_basic.4y', 'education_basic.6y',
       'education_basic.9y', 'education_high.school', 'education_illiterate',
       'education_professional.course', 'education_university.degree',
       'education_unknown', 'default_no', 'default_unknown', 'default_yes',
       'housing_no', 'housing_unknown', 'housing_yes', 'loan_no',
       'loan_unknown', 'loan_yes', 'contact_cellular', 'contact_telephone',
       'month_apr', 'month_aug', 'month_dec', 'month_jul', 'month_jun',
       'month_mar', 'month_may', 'month_nov', 'month_oct', 'month_sep',
       'day_of_week_fri', 'day_of_week_mon', 'day_of_week_thu',
       'day_of_week_tue', 'day_of_week_wed', 'poutcome_failure',
       'poutcome_nonexistent', 'poutcome_success'],
      dtype='object')