【问题标题】:one-hot encoding single sample pandasone-hot 编码单样本 pandas
【发布时间】:2016-12-23 09:00:26
【问题描述】:

问题陈述:我想对这个单个样本进行一次热编码:

In [2]: single_sample = pd.DataFrame({"Color":['Green']})

             Color 
0            'Green'   

使用与此数据帧相同的 one-hot 编码:

In [3]: df = pd.DataFrame({"Color":['Red', 'Blue', 'Green', 'Orange']})

             Color 
0            'Red'         
1            'Blue'     
2            'Green'       
3            'Orange'

应用 one-hot 编码后,大数据帧如下所示;

In [4]: pd.get_dummies(df)

      Color_Blue  Color_Green  Color_Orange  Color_Red
0              0            0             0          1
1              1            0             0          0
2              0            1             0          0
3              0            0             1          0

我希望单个样本是;

      Color_Blue  Color_Green  Color_Orange  Color_Red
0              0            1             0          0

我想到实现这一点的唯一方法是将单个样本连接到数据帧,然后执行 one-hot 编码操作,或者编写我自己的 one-hot 编码器,我可以将其应用于给定的列。

有没有更好的方法来保存 .get_dummies() 函数应用的操作?

【问题讨论】:

    标签: python pandas encoding


    【解决方案1】:

    您可以逐列使用reindexdf1

    df1 = pd.get_dummies(df)
    print (df1)
       Color_Blue  Color_Green  Color_Orange  Color_Red
    0           0            0             0          1
    1           1            0             0          0
    2           0            1             0          0
    3           0            0             1          0
    
    print (pd.get_dummies(single_sample).reindex(columns=df1.columns, fill_value=0))
       Color_Blue  Color_Green  Color_Orange  Color_Red
    0           0            1             0          0
    

    另一种可能的解决方案是通过list comprehension 创建新列:

    cols = ('Color_' + df.Color.sort_values()).unique().tolist()
    print (cols)
    ['Color_Blue', 'Color_Green', 'Color_Orange', 'Color_Red']
    
    print (pd.get_dummies(single_sample).reindex(columns=cols, fill_value=0))
       Color_Blue  Color_Green  Color_Orange  Color_Red
    0           0            1             0          0
    

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 2023-01-16
      • 2017-02-16
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 2021-04-14
      • 1970-01-01
      相关资源
      最近更新 更多