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

Merge rows with pandas and append the different columns

I have the following dataframe :

CONTACT_ID COMPANY_ID FIRST_NAME SURNAME EMAIL COMPANY_NAME
1 8 Martin GERARD martin.gerard@gmail.com BIG COMPANY
1 87 Martin GERARD martin.gerard@gmail.com LITTLE COMPANY
30 12 Jean DUPOND jean.dupond@aol.com MEGA COMPANY

I’d like to use pandas to convert it like so :

CONTACT_ID FIRST_NAME SURNAME EMAIL COMPANY_ID_1 COMPANY_NAME_1 COMPANY_ID_2 COMPANY_NAME_2
1 Martin GERARD martin.gerard@gmail.com 8 BIGCOMPANY 87 LITTLECOMPANY
30 Jean DUPOND jean.dupond@aol.com 12 MEGA COMPANY

One contact can even have more than two companies.

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

>Solution :

Create list of columns used for create groups, then converte them to index by DataFrame.set_index and counter by GroupBy.cumcount, reshape by DataFrame.unstack with DataFrame.sort_index, flatten MultiIndex and last convert levels from list to columns:

cols = ['CONTACT_ID','FIRST_NAME','SURNAME','EMAIL']

df = (df.set_index([*cols, df.groupby(cols).cumcount().add(1)])
        .unstack(fill_value='')
        .sort_index(axis=1, level=1,sort_remaining=False))

df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
df = df.reset_index()
print (df)
   CONTACT_ID FIRST_NAME SURNAME                    EMAIL COMPANY_ID_1  \
0           1     Martin  GERARD  martin.gerard@gmail.com            8   
1          30       Jean  DUPOND      jean.dupond@aol.com           12   

  COMPANY_NAME_1 COMPANY_ID_2  COMPANY_NAME_2  
0    BIG COMPANY           87  LITTLE COMPANY  
1   MEGA COMPANY      
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