You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas按国家分组获取各国家Top5高count菜系

解决Pandas按国家分组取每个国家count最高的前5个菜系问题

问题原因

你当前的代码逻辑有误:

  1. 先按['country','cuisines']分组后,每个分组已经是国家+菜系的唯一组合,每组仅对应1个count值,此时调用nlargest(5)完全起不到按国家取top5菜系的作用。
  2. 后续直接对整个DataFrame取前5行,得到的是全局范围内的top5,并非每个国家各自的top5。

正确实现方式

以下两种方法都能满足你的需求,基于你的df3数据:

方法1:排序后分组取前N(推荐)

先按国家分组,组内按count降序排序,再取每组前5条记录:

# 按国家升序、count降序排序,再按国家分组取前5行
result = df3.sort_values(['country', 'count'], ascending=[True, False]) \
            .groupby('country') \
            .head(5) \
            .reset_index(drop=True)

方法2:用排名筛选

给每个国家内的菜系按count做降序排名,筛选出排名≤5的记录:

# 按国家分组,计算每个菜系的count排名(降序,相同count保留原始顺序)
df3['rank'] = df3.groupby('country')['count'].rank(ascending=False, method='first')
# 筛选排名前5的记录,移除辅助列rank
result = df3[df3['rank'] <= 5].drop(columns='rank').reset_index(drop=True)

样例验证

用你提供的测试数据执行方法1后,得到结果如下:

countrycuisinescount
Australiaitalian19
Australiafrench12
FranceThailand9
FranceJapanese5
Italy.Italian3

完全符合每个国家取top5(国家内菜系不足5个时返回全部)的需求。

内容的提问来源于stack exchange,提问作者jeannetton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:10:45