3
$\begingroup$

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 :)

enter image description here

$\endgroup$
  • $\begingroup$ Are the values in that column strings? $\endgroup$ – marco_gorelli Sep 28 '18 at 15:00
  • $\begingroup$ @marco_gorelli yea $\endgroup$ – Programmer Sep 28 '18 at 15:04
6
$\begingroup$

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
$\endgroup$
0
$\begingroup$
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
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.