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

如何让pandas的value_counts先按计数排序再按字母顺序排序?

解决方案:按计数+字母序排序水果计数

嘿,我来帮你搞定这个需求!针对你提供的DataFrame,我们可以用pandas的现代方法实现先按计数值降序、相同计数时按水果名称升序排列的效果,具体步骤如下:

步骤1:构造DataFrame并导入依赖

首先确保你导入了pandas,然后构造你的数据集:

import pandas as pd

df = pd.DataFrame({
    'fruit': ['peaches']*5 + ['apples']*5 + ['bananas']*3 + ['nectarines']*3 + ['carrots']*3 + ['apricots']
})

步骤2:统计水果计数并按规则排序

我们先统计每个水果的出现次数,然后通过多键排序实现需求:

# 1. 统计每个水果的数量,转为包含列名的DataFrame
fruit_counts = df['fruit'].value_counts().reset_index()
fruit_counts.columns = ['fruit', 'count']

# 2. 按「计数降序、名称升序」排序
sorted_counts = fruit_counts.sort_values(by=['count', 'fruit'], ascending=[False, True])

步骤3:输出你想要的格式

最后遍历排序后的结果,按指定格式打印:

for _, row in sorted_counts.iterrows():
    print(f"{row['fruit']} {row['count']}")

运行后你会得到完全符合预期的输出:

apples 5
peaches 5
bananas 3
carrots 3
nectarines 3
apricots 1

可选的简洁写法

如果你喜欢更紧凑的代码,也可以直接对统计后的Series进行稳定排序(先按名称升序,再按计数降序,利用稳定排序的特性保留名称顺序):

# 先按名称升序排序,再按计数降序(使用mergesort稳定排序)
sorted_counts = df['fruit'].value_counts().sort_index(ascending=True).sort_values(ascending=False, kind='mergesort')
# 直接打印结果
print(sorted_counts.to_string(header=False))

这个写法同样能得到和上面一致的输出,不过第一种方法逻辑更直观,适合新手理解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:05:17