【问题标题】:One-hot encoding for words which occur in multiple columns多列中出现的单词的 One-hot 编码
【发布时间】:2021-02-16 09:05:32
【问题描述】:

我想从分类数据创建即时编码数据,您可以在此处查看。

        Label1          Label2        Label3  
0   Street fashion        Clothing       Fashion
1         Clothing       Outerwear         Jeans
2     Architecture        Property      Clothing
3         Clothing           Black      Footwear
4            White      Photograph        Beauty

问题(对我来说)是一个特定的标签(例如服装)可以在标签 1、标签 2 或标签 3 中。我试过 pd.get_dummies 但这会创建如下数据:

Label1_Clothing  Label2_Clothing    Label3_Clothing  
0      0                 1                 0
1      1                 0                 0
2      0                 0                 1

有没有办法让每个标签只有一个虚拟变量列?而是:

Label_Clothing  Label_Street Fashion    Label_Architecture  
0      1                 1                 0
1      1                 0                 0
2      1                 0                 1

我是编程新手,很高兴得到您的帮助。

最好, 贝尔纳多

【问题讨论】:

    标签: python pandas machine-learning one-hot-encoding dummy-variable


    【解决方案1】:

    您可以将您的数据框堆叠成一个Series,然后从中获取假人。从那里您可以利用外部级别的最大值将数据折叠回其原始形状,同时保持标签的位置:

    dummies = pd.get_dummies(df.stack()).max(level=0)
    
    print(dummies)
       Architecture  Beauty  Black  Clothing  Fashion  Footwear  Jeans  Outerwear  Photograph  Property  Street fashion  White
    0             0       0      0         1        1         0      0          0           0         0               1      0
    1             0       0      0         1        0         0      1          1           0         0               0      0
    2             1       0      0         1        0         0      0          0           0         1               0      0
    3             0       0      1         1        0         1      0          0           0         0               0      0
    4             0       1      0         0        0         0      0          0           1         0               0      1
    

    【讨论】:

    • 非常感谢!我希望你有一个非常愉快的一天/晚上:)
    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2017-12-09
    • 2019-11-18
    • 2017-07-02
    • 2019-10-27
    • 2017-06-21
    相关资源
    最近更新 更多