d = {'col': ['baked', 'beans', 'baked', 'baked', 'beans']}
df = pd.DataFrame(data=d)
print(df)
df = pd.concat([df] * 100000).reset_index(drop=True)
df1, df2, df3, df4 = df.copy(), df.copy(), df.copy(), df.copy()

def a(df):
    df['col'] = pd.factorize(df.col)[0]
return df

def a1(df):
    idx, _ = pd.factorize(df.col)
df['col'] = idx
return df

def b(df):
    df['col'] = np.unique(df['col'], return_inverse=True)[1]
return df

def b1(df):
    _, idx = np.unique(df['col'], return_inverse=True)
df['col'] = idx
return df
print(a(df1))
print(a1(df2))
print(b(df3))
print(b1(df4))
Python - Speed up for converting a categorical variable to it's numerical index