简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM