如何将值单元格作为pandas数据帧中的新列

时间:2016-12-05 17:40:22

标签: python pandas dataframe

我有一个如下数据框:

    Labels
1   Nail_Polish,Nails
2   Nail_Polish,Nails
3   Foot_Care,Targeted_Body_Care
4   Foot_Care,Targeted_Body_Care,Skin_Care

我想生成以下矩阵:

    Nail_Polish   Nails   Foot_Care   Targeted_Body_Care   Skin_Care
1       1           1         0                0               0
2       1           1         0                0               0
3       0           0         1                1               0
4       0           0         1                1               1

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:4)

使用str.get_dummies

df2 = df['Labels'].str.get_dummies(sep=',')

结果输出:

   Foot_Care  Nail_Polish  Nails  Skin_Care  Targeted_Body_Care
1          0            1      1          0                   0
2          0            1      1          0                   0
3          1            0      0          0                   1
4          1            0      0          1                   1