简体   繁体   English

pandas groupby 聚合函数中重复最多的字符串

[英]Most repeated string in pandas groupby aggregate fucntion

I have a data like this我有这样的数据

Customer ID客户ID Amount数量 Location地点
1 1 2500 2500 India印度
2 2 3000 3000 USA美国
1 1 1000 1000 India印度
2 2 500 500 India印度
1 1 2500 2500 India印度
1 1 500 500 USA美国
2 2 500 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:如何在 pandas 中使用 groupby 聚合 function 在客户级别返回 Amount 列和 Location 列中最重复字符串的总和:

Customer ID客户ID Amount数量 Location地点
1 1 5500 5500 India印度
2 2 400 400 USA美国

Use GroupBy.agg with aggregate functions, for Series.mode is necessary add iat[0] for get first value if multiple top values:GroupBy.agg与聚合函数一起使用,对于Series.mode ,如果有多个最高值,则必须添加iat[0]以获得第一个值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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