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

如何在Pandas中按Class、Title分组后对数据进行降序排序?

实现Pandas数据的分组排序

情况1:仅按分组规则排序(不聚合)

如果需求是让数据先按class分组,同一class内按title分组,且每个title组内的event_count降序排列,直接使用sort_values指定多列排序规则即可:

import pandas as pd

df = pd.DataFrame({
    'class': ['Opn', 'Opn', 'MA', 'CoNo', 'Opn'],
    'title': ['Title1', 'Title1', 'Title2', 'Title3', 'Title2'],
    'event_count': [16, 11, 8, 7, 5]
})

# 排序逻辑:先按class升序,再按title升序,最后按event_count降序
sorted_df = df.sort_values(by=['class', 'title', 'event_count'], ascending=[True, True, False])
print(sorted_df)

输出结果:

class   title  event_count
0     Opn  Title1           16
1     Opn  Title1           11
4     Opn  Title2            5
2      MA  Title2            8
3    CoNo  Title3            7

情况2:按分组聚合后排序

如果需要先对每个class+title的event_count求和,再在每个class内按聚合后的总数降序排列,同时保留原行并按event_count降序,可按以下步骤操作:

# 计算每个class+title的event_count总和
grouped_total = df.groupby(['class', 'title'])['event_count'].sum().reset_index(name='total')

# 将聚合结果合并回原数据
df_merged = df.merge(grouped_total, on=['class', 'title'])

# 按class升序、聚合总数降序、event_count降序排序,最后删除辅助列
sorted_df = df_merged.sort_values(by=['class', 'total', 'event_count'], ascending=[True, False, False]).drop('total', axis=1)
print(sorted_df)

本例中输出结果与情况1一致(因Opn分组下Title1的总数远大于Title2),若数据分布不同,会体现出聚合排序的差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:17:30