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

Pandas Split String in colum into colums with 0/1 ; get dummies on all characters of a string

Very likely this question was answered, but I can not find a good title. I have this pandas data structure, based on a given excel sheet:

other columns Code
… ABC
… CAB
… R

I want to get this:

other columns A B C R
… 1 1 1 0
… 1 1 1 0
… 0 0 0 1

Of course, I could iterate over each row and so this manually, but all ideas in my head will either be slow or memory consuming or both.

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

What is the one line solution here?

>Solution :

You can use str.get_dummies with an empty separator to get all letters:

df['Code'].str.get_dummies(sep='')

joining to original data:

df2 = df.drop('Code', axis=1).join(df['Code'].str.get_dummies(sep=''))

output:

  other columns   A  B  C  R
0           ...   1  1  1  0
1           ...   1  1  1  0
2           ...   0  0  0  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