转换多个分类列

Transform multiple categorical columns

在我的数据集中,我有两个要计算的分类列。这两列都包含国家,有些重叠(出现在两列中)。我想在 column1 和 column2 中为同一个国家提供相同的数字。

我的数据看起来有点像:

import pandas as pd

d = {'col1': ['NL', 'BE', 'FR', 'BE'], 'col2': ['BE', 'NL', 'ES', 'ES']}
df = pd.DataFrame(data=d)
df

目前我正在将数据转换为:

from sklearn.preprocessing import LabelEncoder
df.apply(LabelEncoder().fit_transform)

然而这并没有区分FR和ES。有没有其他简单的方法可以得到下面的输出?

o = {'col1': [2,0,1,0], 'col2': [0,2,4,4]}
output = pd.DataFrame(data=o)
output

这是一种方法

df.stack().astype('category').cat.codes.unstack()
Out[190]: 
   col1  col2
0     3     0
1     0     3
2     2     1
3     0     1

s=df.stack()
s[:]=s.factorize()[0]
s.unstack()
Out[196]: 
   col1  col2
0     0     1
1     1     0
2     2     3
3     1     3

您可以先将 LabelEncoder() 与数据框中的唯一值匹配,然后进行转换。

le = LabelEncoder()
le.fit(pd.concat([df.col1, df.col2]).unique()) # or np.unique(df.values.reshape(-1,1))

df.apply(le.transform)
Out[28]: 
   col1  col2
0     3     0
1     0     3
2     2     1
3     0     1

np.uniquereturn_invesere。尽管您随后需要重建 DataFrame。

pd.DataFrame(np.unique(df, return_inverse=True)[1].reshape(df.shape),
             index=df.index,
             columns=df.columns)

   col1  col2
0     3     0
1     0     3
2     2     1
3     0     1