Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dataframe Multi-Label List Column to One-Hot

How can I go from a string column with list of labels to the format shown below?

This is what I have:

pd.DataFrame([["a",1],["b","1, 2"],["c","1,3,4"]], columns =['id', 'label'])

This is what I want:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pd.DataFrame([["a",1,0,0,0],["b",1,1,0,0],["c",1,0,1,1]], columns =['id', '1', '2', '3', '4'])

I can do this with a for loop but the execution time is horrendous.

>Solution :

Use .str.get_dummies():

df = pd.concat([df.drop('label', axis=1), df['label'].str.get_dummies(',')], axis=1)

Output:

>>> df
  id  1  2  3  4
0  a  1  0  0  0
1  b  1  1  0  0
2  c  1  0  1  1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading