encode all categorical variables to numerical code example

Example 1: pandas categorical to numeric

#this will label the different catagories as 0,1,2,3....
dataset["sex"] = dataset["sex"].astype('category').cat.codes

Example 2: transform categorical variables python

from sklearn.preprocessing import LabelEncoder

lb_make = LabelEncoder()
obj_df["make_code"] = lb_make.fit_transform(obj_df["make"])
obj_df[["make", "make_code"]].head(11)

Example 3: 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])

Tags:

Css Example