【问题标题】:How to convert (Not-One) Hot Encodings to a Column with Multiple Values on the Same Row如何将(非一个)热编码转换为同一行具有多个值的列
【发布时间】: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 编码的问题(例如 12),但答案依赖于每行只有一个二进制类处于活动状态,而我的数据可以在同一行中有多个类处于活动状态.

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

使用在这两个问题(1 & 2)中找到的想法,我能够想出一个解决方案,但它需要一个普通的 python for 循环来遍历行,我怀疑这将是与完全使用 pandas 的解决方案相比,速度较慢。

输入数据帧可以使用实际的布尔值而不是整数编码,如果它使事情变得更容易的话。输出可以是数据帧或序列;我最终会将结果列添加到更大的数据框中。如果可以提供更好的解决方案,我也愿意使用numpy,但否则我宁愿坚持使用pandas

【问题讨论】:

    标签: python pandas numpy dataframe one-hot-encoding


    【解决方案1】:

    这是一个使用 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
    

    【讨论】:

      【解决方案2】:

      您可以使用DataFrame.dot,这比遍历数据框中的所有行要多得多faster

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 2019-05-22
        • 2018-11-04
        • 2022-06-21
        相关资源
        最近更新 更多