python - 多列上的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
上面的例子只是一种对我的列进行编码的方法,我的目标是尝试不同的方法,还有其他库可以进行这种编码,而无需将变换方法仅应用于拟合的列(无需从头开始编写每个类别编码方法)?
解决方案
您可以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
推荐阅读
- c# - vuforia 不接受 AR 统一应用程序的旧脚本
- javascript - TypeError:无法在我的 next.js 应用程序中读取未定义的属性“uri”
- python - 使用 Pandas 在标头中传递 API 密钥
- javascript - 如何从命名空间导出,访问默认值?
- vb.net - 在从另一个类继承的类中创建一个表。VB.net
- node.js - 距离可以使用命令的时间从 60 秒更改为 1 分钟
- np - 为什么我们需要一个中间顶点来将 DHP 减少到 UHP?
- reactjs - React Typescript标签拖动到文本区域
- python-3.x - 条件计算的中间层损失计算
- http - 如何在 Clojure 中使用 POST 处理程序接收 edn?(以及如何发送)