我有2个具有相同列标题的数据帧.我希望对它们进行热编码.我不能一个一个地执行它们.我希望将两个数据帧附加在一起,然后执行热编码,然后将它们拆分为2个数据帧,并在每个数据帧上再次使用标题.
下面的代码逐个执行热编码,而不是合并它们然后热编码.
train = pd.get_dummies(train, columns= ['is_discount', 'gender', 'city'])
test = pd.get_dummies(test, columns= ['is_discount', 'gender', 'city'])
解决方法:
使用带有键的concat然后分开即
#Example Dataframes
train = pd.DataFrame({'x':[1,2,3,4]})
test = pd.DataFrame({'x':[4,2,5,0]})
# Concat with keys
temp = pd.get_dummies(pd.concat([train,test],keys=[0,1]), columns=['x'])
# Selecting data from multi index
train,test = temp.xs(0),temp.xs(1)
输出:
#Train x_0 x_1 x_2 x_3 x_4 x_5 0 0 1 0 0 0 0 1 0 0 1 0 0 0 2 0 0 0 1 0 0 3 0 0 0 0 1 0 #Test x_0 x_1 x_2 x_3 x_4 x_5 0 0 0 0 0 1 0 1 0 0 1 0 0 0 2 0 0 0 0 0 1 3 1 0 0 0 0 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。