Python PANDAS:如何将一键编码反向分类 [英] Python PANDAS: How to Reverse One-Hot Encoding Back to Categorical
本文介绍了Python PANDAS:如何将一键编码反向分类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据框的总体布局如下:
I have a dataframe with the following general layout:
id,ind_1,ind_2_ind_3
1,0,1,0
1,1,0,0
2,0,1,0
2,0,0,1
3,0,0,1
3,1,0,0
我想添加一列,当其值为'1'时其值为原始指标名称,该字段应如下所示:
I would like to add an additional column whose values are the original indicator names when they are '1' which should look like this:
id,ind_1,ind_2,ind_3,ind_all
1,0,1,0,ind_2
1,1,0,0,ind_1
2,0,1,0,ind_2
2,0,0,1,ind_3
3,0,0,1,ind_3
3,1,0,0,ind_1
欢迎任何提示!
推荐答案
您需要
df['ind_all'] = (df.iloc[:, 1:] == 1).idxmax(1)
id ind_1 ind_2 ind_3 ind_all
0 1 0 1 0 ind_2
1 1 1 0 0 ind_1
2 2 0 1 0 ind_2
3 2 0 0 1 ind_3
4 3 0 0 1 ind_3
5 3 1 0 0 ind_1
这篇关于Python PANDAS:如何将一键编码反向分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文