如何将(NotOne)热编码转换为同一行上具有多个值的列

2024-04-27 14:55:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上想扭转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                  

关于反转一个热编码有很多问题(例如1&;2),但答案取决于每行只有一个二进制类处于活动状态,而我的数据在同一行中可以有多个类处于活动状态

This question接近于解决我需要的问题,但它的多个类在不同的行上分开。我需要我的结果是由分隔符(例如“,”)连接的字符串,这样输出的行数与输入的行数相同

使用这两个问题(1&;2)中的思想,我能够想出一个解决方案,但它需要一个普通的python for循环来迭代行,我怀疑这与完全使用pandas的解决方案相比会很慢

输入数据帧可以使用实际的布尔值,而不是整数编码,如果它使事情变得更简单的话。输出可以是数据帧或序列;我最终将把结果列添加到一个更大的数据帧中。如果允许更好的解决方案,我也愿意使用numpy,但如果不允许,我更愿意使用pandas


Tags: 数据dataframepandasinputoutputexample解决方案one
2条回答

下面是一个使用python列表理解来迭代每一行的解决方案:

import pandas as pd

def reverse_hot_encoding(df, sep=', '):
    df = df.astype(bool)
    l = [sep.join(df.columns[row]) for _, row in df.iterrows()]
    return pd.Series(l)

if __name__ == '__main__':
    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(reverse_hot_encoding(example_input))

以下是输出:

0         three, four
1    one, three, four
2               three
3          one, three
4                    
dtype: object

您可以执行^{},这比迭代数据帧中的所有行要faster得多:

df.dot(df.columns + ', ').str.rstrip(', ')

0         three, four
1    one, three, four
2               three
3          one, three
4                    
dtype: object

相关问题 更多 >