首页 > 解决方案 > 多列上的python类别编码器

问题描述

我需要将几个类别编码器测试到包含相同值的不同列。所有值都出现在列中,但不在同一行中。例如,我可以:

dft = pd.DataFrame({
'col0':["a", "b", "a", "c", "b", "d"], 
'col1':["c", "d", "b", "d", "c", "c"],
'col2':["b", "a", "c", "b", "a", "a"],
})

  col0 col1 col2
0    a    c    b
1    b    d    a
2    a    b    c
3    c    d    b
4    b    c    a
5    d    c    a

我不能在第一排"a", "c", "c"

为了对列进行编码,我使用了 Python 库类别编码器。问题是我需要用一列安装编码器,然后在多列上应用编码。例如给出df这样的:

dft = pd.DataFrame({
'col0':["a", "b", "a", "c", "b", "d"], 
'col1':["c", "d", "b", "d", "c", "c"]})

  col0 col1
0    a    c
1    b    d
2    a    b
3    c    d
4    b    c
5    d    c

我想要的是:

  col0 col1  a  b  c  d
0    a    c  1  0  1  0
1    b    d  0  1  0  1
2    a    b  1  1  0  0
3    c    d  0  0  1  1
4    b    c  0  1  1  0
5    d    c  0  0  1  1

但是使用category encoders库我必须对fit列应用并将其应用于transform同一列。在列上使用category encoders会发生这种情况:

dft = pd.DataFrame({
'col0':["a", "b", "a", "a", "b", "b"], 
'col1':["c", "d", "c", "d", "c", "c"],
})
encoder = ce.OneHotEncoder(cols=None, use_cat_names=True) # encoding example to visualize better the problem
encoder.fit(dft['col0'])

encoder.transform(dft['col0'])

输出:

   col0_a  col0_b  col0_c  col0_d
0       1       0       0       0
1       0       1       0       0
2       1       0       0       0
3       0       0       1       0
4       0       1       0       0
5       0       0       0       1

然后将转换应用于另一列:

encoder.transform(dft['col1']) 

输出:

KeyError: 'col0'

如果在两列上都进行了拟合(因为 col0 和 col1 包含相同的唯一值),则输出为:

encoder.fit(dft[['col0','col1']])
encoder.transform(dft[['col0','col1']])

       col0_a  col0_b  col0_c  col0_d  col1_c  col1_d  col1_b
0       1       0       0       0       1       0       0
1       0       1       0       0       0       1       0
2       1       0       0       0       0       0       1
3       0       0       1       0       0       1       0
4       0       1       0       0       1       0       0
5       0       0       0       1       1       0       0

上面的例子只是一种对我的列进行编码的方法,我的目标是尝试不同的方法,还有其他库可以进行这种编码,而无需将变换方法仅应用于拟合的列(无需从头开始编写每个类别编码方法)?

标签: pythonpandasscikit-learncategorical-data

解决方案


您可以stack对数据框进行重塑,然后用于为堆叠框str.get_dummies创建指标sum变量的数据框,最后采用level=0

enc = dft.stack().str.get_dummies().sum(level=0)
out = dft.join(enc)

>>> out

  col0 col1  a  b  c  d
0    a    c  1  0  1  0
1    b    d  0  1  0  1
2    a    b  1  1  0  0
3    c    d  0  0  1  1
4    b    c  0  1  1  0
5    d    c  0  0  1  1

推荐阅读