简体   繁体   中英

Most repeated string in pandas groupby aggregate fucntion

I have a data like this

Customer ID Amount Location
1 2500 India
2 3000 USA
1 1000 India
2 500 India
1 2500 India
1 500 USA
2 500 USA

How can I use groupby aggregate function in pandas to return the sum of Amount column and most repeated string in Location column on customer level:

Customer ID Amount Location
1 5500 India
2 400 USA

Use GroupBy.agg with aggregate functions, for Series.mode is necessary add iat[0] for get first value if multiple top values:

df.groupby('Customer ID').agg({'Amount':'sum', 'Location': lambda x: x.mode().iat[0]})

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