How can i "merge" rows groupby having same values in Pandas dataframe?

Viewed 559

link to table

The name of my dataframe is df.

I want to combine the rows having the same Borough and same PostalCode with Neighborhood separated by commas. But I'm not able to get it. Can anyone please help me with it?

2 Answers

you have to first group by the two first column and then apply a transform for joining the result.

df['Neighborhood ']= df.groupby(['PostalCode ','Borough'])['Neighboudhood'].transform(lambda x: ','.join(x))
df = df.drop_duplicates()

You can use this:

df = df.groupby(['PostalCode','Borough'])['Neighbourhood'].agg(','.join)

output sample for the two rows:

CR0  Croydon    Addington,Addiscombe
Related