How cell values ​​like new columns in pandas dataframe

I have a dataframe as shown below:

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

I want to generate the following matrix:

    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

How can i achieve this?

+4
source share
1 answer

Use str.get_dummies:

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

Result:

   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
+4
source

Source: https://habr.com/ru/post/1662872/


All Articles