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

How to merge duplicate rows in pandas

import pandas as pd
df = pd.DataFrame({'id':['A','A','A','B','B','B','C'],'name':[1,2,3,4,5,6,7]})
print(df.to_string(index=False))

As of now the output for above code is:

id  name
 A     1
 A     2
 A     3
 B     4
 B     5
 B     6
 C     7

But I am expeting its output like:

id    name
A     1,2,3
B     4,5,6
C     7

I ain’t sure how to do it, I have tried several other codes but didn’t work for me. Please help in solving this.

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 :

If you want a comma separated list of values, you can aggregate using join, noting that you have to convert the values to strings first:

df2 = df.groupby('id', as_index=False).agg(lambda x: ','.join(map(str, x)))
print(df2.to_string(index=False))

Output:

id  name
 A 1,2,3
 B 4,5,6
 C     7

If you just want a list of values, aggregate using list:

df2 = df.groupby('id', as_index=False).agg(list)
print(df2.to_string(index=False))

Output:

id      name
 A [1, 2, 3]
 B [4, 5, 6]
 C       [7]
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