转换多个分类列

Tox*_*Tox 8 python python-3.x pandas scikit-learn categorical-data

在我的数据集中,我想列举两个分类列。两列均包含国家/地区,有些重叠(均出现在两列中)。我想在同一国家的column1和column2中给出相同的数字。

我的数据看起来像:

import pandas as pd

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

目前,我正在像这样转换数据:

from sklearn.preprocessing import LabelEncoder
df.apply(LabelEncoder().fit_transform)
Run Code Online (Sandbox Code Playgroud)

但是,这在FR和ES之间没有区别。是否有另一种简单的方法可以得到以下输出?

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

WeN*_*Ben 8

这是一种方法

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

要么

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
Run Code Online (Sandbox Code Playgroud)


Mic*_*ner 5

您可以先将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
Run Code Online (Sandbox Code Playgroud)