首页 > 解决方案 > 如何将返回的 one-hot 编码列合并到原始数据帧?

问题描述

我有banking_dataframe21 个不同的列,一个是目标,其中 10 个是数字特征,其中 10 个是分类特征。我使用get_dummiespandas 的方法将分类数据转换为 one-hot 编码。返回的数据框有 74 列。现在,我想将编码数据帧与原始数据帧合并,所以我的最终数据应该具有分类列的单热编码值,但数据帧的原始大小即;21 列。

Pandas 的 get_dummies 函数链接:

调用get_dummies分类特征的代码片段

encoded_features = pd.get_dummies(banking_dataframe[categorical_feature_names])

标签: pythonpandasdataframemachine-learningone-hot-encoding

解决方案


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()

推荐阅读