python Pandas : How to Reverse One-Hot Encoding Back to Categorical

标签 python pandas numpy

<分区>

我有一个具有以下总体布局的数据框:

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”时的原始指标名称,应该如下所示:

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 : How to Reverse One-Hot Encoding Back to Categorical,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49372640/

相关文章:

python - 查询日期和价格数据的矢量化方式

python - 用 Python 制作音乐

python - functools.partial(func,myArgs) 的等价类是什么?

Python list.clear 复杂性

python - 查找(bash 命令)不适用于子进程?

python - SQLAlchemy 和 Pandas : How to query columns with a different label?

python - 从特定索引开始的数据框 cummin 列

python - Pandas 从组中获取列的第一个和最后一个值

python - 旧Python代码的更新

python - 在特定轴上运行的 Numpy power ufunc