df = pd.DataFrame([['a', 'b'], ['b', 'c'], ['d', 'a']])
v = df.stack().unique()
v.sort()
f = pd.factorize(v)
m = pd.Series(f[0], f[1])
df.stack().map(m).unstack()
How to remap ids to consecutive numbers quickly