python - 如何将返回的 one-hot 编码列合并到原始数据帧?
问题描述
我有banking_dataframe
21 个不同的列,一个是目标,其中 10 个是数字特征,其中 10 个是分类特征。我使用get_dummies
pandas 的方法将分类数据转换为 one-hot 编码。返回的数据框有 74 列。现在,我想将编码数据帧与原始数据帧合并,所以我的最终数据应该具有分类列的单热编码值,但数据帧的原始大小即;21 列。
Pandas 的 get_dummies 函数链接:
调用get_dummies
分类特征的代码片段
encoded_features = pd.get_dummies(banking_dataframe[categorical_feature_names])
解决方案
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
# creating a toy data frame to test
df = pd.DataFrame({'Gender': ['M', 'F', 'M', 'M', 'F', 'F', 'F']})
# instantiating and transforming the 'Gender' column of the df
one_hot = OneHotEncoder()
encoded = one_hot.fit_transform(df[['Gender']])
# one_hot object has an attribute 'categories_', which stores the array
# of categories sequentially, and those categories can serve as
# new columns in our data frame.
df[one_hot.categories_[0]] = encoded.toarray()
推荐阅读
- android - 每日重复通知,已弃用 N̶o̶t̶i̶f̶i̶c̶a̶t̶i̶o̶n̶C̶o̶m̶p̶a̶t̶.̶B̶u̶i̶l̶d̶e̶r̶
- audio - 捕获计算机屏幕和音频上的所有内容。涉及哪些技术/API?
- c++ - Qt程序使用Matlab dll,在本地盘初始化成功,在My U盘初始化失败
- jenkins - 如何将 Jenkins 项目构建号、构建日期和构建时间存储到文件中?
- visual-studio-2015 - 本地主机拒绝连接错误 VIsual Studio 2015
- neo4j - Neo4j Cypher UNWIND 键
- c# - 我们如何在应用程序中使用刷新令牌?
- mongodb - $push 在 mongoDB 中不起作用
- vb.net - 四舍五入到小数点后两位
- javascript - 如何使用 jAutoCalc 插件将多行动态表写入 Mysql 数据库