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

使用Pandas Groupby、agg聚合分类变量后无法排序count列求助

解决方案

你的问题出在apply(lambda x: x.sort_values(ascending=False))这一步——当前分组是['City','Complaint Type'],每个子组只有一行数据,排序操作根本起不到作用。以下两种方法可以解决你的需求:

方法1:多列直接排序(推荐)

直接通过sort_values指定多排序条件:先按City升序排列,同一城市内按count降序排列,无需额外操作:

df_perCity.groupby(['City','Complaint Type'])['Complaint Type']
          .agg(['count'])
          .sort_values(by=['City', 'count'], ascending=[True, False])

方法2:按City分组后内部排序

如果需要保留每个City作为独立分组的结构,可先聚合再按City分组,对每个分组内部的count列排序:

(df_perCity.groupby(['City','Complaint Type'])['Complaint Type']
           .agg(['count'])
           .groupby('City', group_keys=False)
           .apply(lambda g: g.sort_values('count', ascending=False)))

group_keys=False可以避免生成多余的分组索引层级,保持结果结构整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:20:28