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

Convert rows to columns and enter 0 and 1 for matches in python

I have a pandas data frame like this:

Original data set

and I need to convert it into the below:

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

Output data set

So, the unique values in column ‘camps’ part of the original data set, gets turned into columns with values 0 and 1 for each id. How can I achieve this using Pandas or anything else in Python? Any help is greatly appreciated. Thanks

Below is the code to create the original data set:

import pandas as pd
cust = {'id': [212175, 286170, 361739, 297438, 415712, 415777, 261700, 314624, 170365, 333254],
        'camps': [':_Camp1_CC SC_Statemt_CCSTMT', ':_Camp1_CC SC_Statemt_CCSTMT', ':_Camp1_Free_DS0742203H_BD03', 
                       ':_Camp1_Over_EO3982112A_BD07', ':_Camp1_Over_EO4022202A_BD16', ':_Camp1_Over_EO4022202A_BD16', 
                      ':_Camp1_AS07_DS0722204H_DD02', ':_Camp1_AS07_DS0722204H_DD02', ':_Camp1_AS07_DS0722204H_DD02', 
                      ':_Camp1_AS07_DS0722204H_DD02']}

cust_df = pd.DataFrame(cust)

>Solution :

A possible solution, based on pd.crosstab:

pd.crosstab(cust_df.id, cust_df.camps)

Output:

camps   :_Camp1_AS07_DS0722204H_DD02  ...  :_Camp1_Over_EO4022202A_BD16
id                                    ...                              
170365                             1  ...                             0
212175                             0  ...                             0
261700                             1  ...                             0
286170                             0  ...                             0
297438                             0  ...                             0
314624                             1  ...                             0
333254                             1  ...                             0
361739                             0  ...                             0
415712                             0  ...                             1
415777                             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

Discover more from Dev solutions

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

Continue reading