categorical data to numerical data python code example

Example 1: panda categorical data into numerica

sex = train_dataset['Sex'].replace(['female','male'],[0,1])
print(sex)

Example 2: To convert categorical data to numerical

cat_cols = ['Item_Identifier', 'Item_Fat_Content', 'Item_Type', 'Outlet_Identifier', 
         'Outlet_Size', 'Outlet_Location_Type', 'Outlet_Type', 'Item_Type_Combined']
enc = LabelEncoder()

for col in cat_cols:
    train[col] = train[col].astype('str')
    test[col] = test[col].astype('str')
    train[col] = enc.fit_transform(train[col])
    test[col] = enc.transform(test[col])