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

Time:02-10

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.

What is the one line solution here?

CodePudding user response:

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
  • Related