# A single column has many values per row, separated by a comma. How to create an individual column for each of these?

As you can see below, I have a column called code with multiple values per row, separated by a comma. How can I create a column for each of these codes and make them all binary values?

i.e. code6254, code5854 etc...., where all these columns will be of binary value 0 or 1 depending on whether that row has the code or not? Thanks in advance :)

• Are the values in that column strings? – ignoring_gravity Sep 28 '18 at 15:00
• @marco_gorelli yea – Programmer Sep 28 '18 at 15:04

It would be better if you could provide some code which allows us to reproduce at least part of your DataFrame, such as this:

import pandas as pd
df = pd.DataFrame({'code': ['6254', '5854, 5676, 7265, 6051', '5815']})


At the start, your dataframe looks like this:

                     code
0                    6254
1  5854, 5676, 7265, 6051
2                    5815


A possible solution would be to do this:

df['code'].str.get_dummies(sep=', ').add_prefix('code')


which gives you this:

   code5676  code5815  code5854  code6051  code6254  code7265
0          0          0          0          0          1          0
1          1          0          1          1          0          1
2          0          1          0          0          0          0

ind=df2.columns.tolist().index('Ticker')

x=0

df3=pd.DataFrame(columns=df2.columns.tolist())

for i in df2.values.tolist():

l1=i[ind].split(';')
for j in l1:
x=x+1
i1=i[:ind]
i1.extend([j])
df3.loc[str(x)]=i1
df3