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

如何按照自定义季度列表对Pandas DataFrame的行进行排序

如何按照自定义季度列表对Pandas DataFrame的行进行排序

我来帮你解决这个问题~你遇到的问题主要有两个原因:一是reindex默认是根据DataFrame的索引来匹配的,而你的索引是默认的0-5,和sortTo里的季度值不匹配;二是你没有把reindex的结果赋值给新变量(或者覆盖原df),所以原数据没变化。下面给你两种靠谱的解决方法:

方法一:通过设置索引+重新索引实现排序

这种方法的思路是先把QuarterYear列设为DataFrame的索引,这样reindex就能根据你自定义的sortTo列表来对齐行,最后再把索引变回普通列:

import pandas as pd

# 你的原始数据
data = {'QuarterYear': ["Q1 2024", "Q2 2024", "Q3 2023", 'Q3 2024', "Q4 2023", "Q4 2024"], 
        'data1': [5, 6, 2, 1, 10, 3], 
        'data2': [12, 4, 2, 7, 2, 9]}
sortTo = ["Q3 2023", "Q4 2023", "Q1 2024", 'Q2 2024', "Q3 2024", "Q4 2024"]
df = pd.DataFrame(data)

# 设置QuarterYear为索引 → 按sortTo重新索引 → 重置索引为普通列
df_sorted = df.set_index('QuarterYear').reindex(sortTo).reset_index()
print(df_sorted)

运行后你会得到符合预期的排序结果:

QuarterYear  data1  data2
0     Q3 2023      2      2
1     Q4 2023     10      2
2     Q1 2024      5     12
3     Q2 2024      6      4
4     Q3 2024      1      7
5     Q4 2024      3      9

方法二:用分类数据类型实现自定义排序

这种方法更灵活,适合后续还要多次按这个顺序排序的场景。我们可以把QuarterYear列转为有序分类,指定分类顺序为sortTo,之后用sort_values就能直接按自定义顺序排序:

import pandas as pd

# 原始数据
data = {'QuarterYear': ["Q1 2024", "Q2 2024", "Q3 2023", 'Q3 2024', "Q4 2023", "Q4 2024"], 
        'data1': [5, 6, 2, 1, 10, 3], 
        'data2': [12, 4, 2, 7, 2, 9]}
sortTo = ["Q3 2023", "Q4 2023", "Q1 2024", 'Q2 2024', "Q3 2024", "Q4 2024"]
df = pd.DataFrame(data)

# 将QuarterYear转为有序分类,指定自定义顺序
df['QuarterYear'] = pd.Categorical(df['QuarterYear'], categories=sortTo, ordered=True)

# 按QuarterYear列排序,重置索引去掉原数字索引
df_sorted = df.sort_values('QuarterYear').reset_index(drop=True)
print(df_sorted)

这个方法的好处是,只要QuarterYear列保持有序分类,之后每次调用sort_values('QuarterYear')都会自动按照你定义的顺序来排,非常方便。

另外补充一下:你之前用reindex没生效,还有一个小细节是reindex默认返回一个新的DataFrame,不会修改原对象,所以你需要把结果赋值给变量(比如df = df.reindex(...))才会看到变化哦~

备注:内容来源于stack exchange,提问作者TIC-FLY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:54:28