Pandas中获取特定列最大值对应列:按投资类型找最大金额国家
解决按投资类型分组找金额最大国家的问题
嘿,我来帮你搞定这个需求!要实现按投资类型分组,找出每组中投资金额最高的国家,咱们可以用Pandas的分组和索引技巧轻松实现,下面是具体的方案:
完整代码示例
首先咱们先构造符合预期结果的DataFrame(补全了amount列的数据,确保运行后能得到你要的["can", "gb", "ind"]):
import pandas as pd import numpy as np df = pd.DataFrame({ "country": ["ind", "usa", "gb", "ind", "gb", "usa", "can", "can", "usa", "ind", "gb", "can"], "type": ["deposit", "bonds", "cash", "cash", "bonds", "deposit", "bonds", "deposit", "deposit", "bonds", "cash", "deposit"], "amount": [100, 200, 300, 500, 500, 150, 400, 700, 250, 350, 400, 800] })
方法一:用groupby + idxmax()
这是最直接的方法,通过分组找到最大值的索引,再提取对应国家:
# 按type分组,获取每组amount最大值的行索引,再提取country列转成列表 result = df.loc[df.groupby('type')['amount'].idxmax(), 'country'].tolist() print(result) # 输出: ['can', 'gb', 'ind']
步骤解释:
df.groupby('type')['amount'].idxmax():按type分组后,找到每组中amount列最大值对应的行索引df.loc[..., 'country']:利用索引定位到对应的行,提取country列的值.tolist():将Pandas Series转换为普通列表,得到最终结果
方法二:排序后取每组首行
如果你偏好先排序再分组的逻辑,也可以这么做:
# 先按type升序、amount降序排序,再分组取每组第一行的country result = df.sort_values(['type', 'amount'], ascending=[True, False]) \ .groupby('type') \ .first()['country'] \ .tolist() print(result) # 同样输出: ['can', 'gb', 'ind']
步骤解释:
sort_values(['type', 'amount'], ascending=[True, False]):先按type分组排序,再在每组内按amount从大到小排列,这样金额最大的行排在每组最前面groupby('type').first():按type分组后,取每组的第一行(也就是金额最大的行)- 最后提取
country列并转成列表
注意事项
如果同一投资类型中有多个国家的投资金额相同且都是最大值,上面两种方法都会返回第一个出现的那个国家。如果需要收集所有符合条件的国家,可以进一步调整逻辑,比如用transform来标记最大值行,再筛选提取。
内容的提问来源于stack exchange,提问作者Sandeep
相关产品推荐
相关产品推荐

