python - 当 test_set 和 train_set 具有不同的唯一值时如何获取虚拟变量?
问题描述
train_set 是:
type
0 a
1 b
2 c
3 d
4 e
如果我使用 pd.get_dummies,我将得到 5 列:
type_a type_b type_c type_d type_e
0 1 0 0 0 0
1 0 1 0 0 0
2 0 0 1 0 0
3 0 0 0 1 0
4 0 0 0 0 1
测试集是:
type
0 a
1 b
2 c
3 d
如果我使用 pd.get_dummies,我只会得到 4 列:
type_a type_b type_c type_d
0 1 0 0 0
1 0 1 0 0
2 0 0 1 0
3 0 0 0 1
我希望它是:
type_a type_b type_c type_d type_e
0 1 0 0 0 0
1 0 1 0 0 0
2 0 0 1 0 0
3 0 0 0 1 0
解决方案
您可以尝试reindex
所有所需的columns
和fill_value=0
:
pd.get_dummies(test_set).reindex(
["type_a", "type_b", "type_c", "type_d", "type_e"], axis=1, fill_value=0)
输出
# type_a type_b type_c type_d type_e
# 0 1 0 0 0 0
# 1 0 1 0 0 0
# 2 0 0 1 0 0
# 3 0 0 0 1 0
推荐阅读
- python - 不能把元组变成字符串
- javascript - Webpack 模块规则测试:匹配包含特定参数的文件
- gradle - 使用 Groovy 应用和测试代码结合 jlink 解决方案来捆绑 JavaFX
- c - 如何在C中将char添加到字符串的末尾?
- reactjs - 无需登录即可打开 PowerBI 页面
- node.js - SheetJS 总是抛出相同的输出
- git - 如何结合 Ansible 在 Git 中配置/描述 Web 应用程序的部署
- javascript - 可以用 React Hooks 定义嵌套组件吗?
- assembly - 64 位汇编中的计算能力
- html - 如何使用 sed 删除 HTML 中的 html 标签、脚本、空行?