Chirag Sable
Chirag Sable

Reputation: 43

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

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?

Upvotes: 3

Views: 1320

Answers (2)

Ehsan
Ehsan

Reputation: 12407

You can use this:

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

output sample for the two rows:

CR0  Croydon    Addington,Addiscombe

Upvotes: 2

user2859710
user2859710

Reputation: 31

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

Upvotes: 2

Related Questions