How to extract feature after Label Encoding for object to numeric conversion

Viewed 77
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
bank=pd.read_csv('train_bank.csv')
df=pd.DataFrame(bank)
df.head()

    ID          Gen     Mar Dep Edu         Sel Income
0   LP001002    Male    No  0   Graduate    No  5849
1   LP001003    Male    Yes 1   Graduate    No  4583
2   LP001005    Male    Yes 0   Graduate    Yes 3000
3   LP001006    Male    Yes 0   Not Grad    No  2583
4   LP001008    Male    No  0   Graduate    No  6000



#Label Encoding for object to numeric conversion
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()

for feat in objList:
    df[feat] = le.fit_transform(df[feat].astype(str))

df.head()

    ID  Gen Mar Dep Edu Sel Income
0   0   1   0   0   0   0   5849
1   1   1   1   1   0   0   4583
2   2   1   1   0   0   1   3000
3   3   1   1   0   1   0   2583
4   4   1   0   0   0   0   6000

But I want those feature names like for "Edu" it Graduate=0 and Not Grad=1. Althoguh I thought it should be the other way for the "Edu" variable. But how to know which code is which feature. And to do like iris data(below) we need the feature_names and how to do that. I am newbiw in Python and trying to do the self project:

fn=iris.feature_names
cn=iris.target_names
fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=500)
tree.plot_tree(classifier.estimators_[0],
               feature_names = fn, 
               class_names=cn,
               filled = True);
fig.savefig('rf_individualtree.png')

I can split the target and feature variable from data, but the names I don't know.

1 Answers

Normally the order of the categories are defined alphabetically, so for example in your Edu column, Grad is 0 and Not Grad would be 1.

You can store your classes as you iterate through your columns, for example:

from sklearn.preprocessing import LabelEncoder
import pandas as pd

le = LabelEncoder()

df = pd.DataFrame({'Gen':['Male','Female','Male'],
'Edu':['Graduate','Not Grad','Graduate']})

categories = {}

for feat in ['Gen','Edu']:
    df[feat] = le.fit_transform(df[feat])
    categories[feat] = le.classes_

Data frame looks like this:

df

   Gen  Edu
0    1    0
1    0    1
2    1    0

And the class orders :

categories
 
{'Gen': array(['Female', 'Male'], dtype=object),
 'Edu': array(['Graduate', 'Not Grad'], dtype=object)}
Related