【发布时间】:2021-01-04 14:02:35
【问题描述】:
我基本上想把this question中提出的过程颠倒过来。
>>> import pandas as pd
>>> example_input = pd.DataFrame({"one" : [0,1,0,1,0],
"two" : [0,0,0,0,0],
"three" : [1,1,1,1,0],
"four" : [1,1,0,0,0]
})
>>> print(example_input)
one two three four
0 0 0 1 1
1 1 0 1 1
2 0 0 1 0
3 1 0 1 0
4 0 0 0 0
>>> desired_output = pd.DataFrame(["three, four", "one, three, four",
"three", "one, three", ""])
>>> print(desired_output)
0
0 three, four
1 one, three, four
2 three
3 one, three
4
有很多关于反转 one-hot 编码的问题(例如 1 和 2),但答案依赖于每行只有一个二进制类处于活动状态,而我的数据可以在同一行中有多个类处于活动状态.
This question 接近于满足我的需求,但它的多个类在不同的行上分开。我需要我的结果是由分隔符连接的字符串(例如“,”),这样输出的行数与输入的行数相同。
使用在这两个问题(1 & 2)中找到的想法,我能够想出一个解决方案,但它需要一个普通的 python for 循环来遍历行,我怀疑这将是与完全使用 pandas 的解决方案相比,速度较慢。
输入数据帧可以使用实际的布尔值而不是整数编码,如果它使事情变得更容易的话。输出可以是数据帧或序列;我最终会将结果列添加到更大的数据框中。如果可以提供更好的解决方案,我也愿意使用numpy,但否则我宁愿坚持使用pandas。
【问题讨论】:
标签: python pandas numpy dataframe one-hot-encoding