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

如何按月份和年份对DataFrame的字符串类型日期列排序?

按月份和年份排序字符串格式的DataFrame列

当然可以按月份和年份对这些字符串列排序,而且完全不需要额外添加前缀!核心思路是把字符串格式的月份年份转换为datetime对象,利用datetime的时间排序特性来调整列的顺序,具体操作步骤如下:

具体实现步骤

  • 首先筛选出所有需要排序的月份列(排除非时间列,比如你的Flavor列)
  • 用pd.to_datetime()把字符串列名转换为datetime对象,以此作为排序的依据
  • 按照转换后的datetime顺序重新排列DataFrame的列

代码示例

假设你的DataFrame名为df,执行以下代码即可完成排序:

import pandas as pd

# 提取所有月份相关的列(排除Flavor列)
month_columns = [col for col in df.columns if col != "Flavor"]

# 按datetime顺序排序列名:key参数指定用转换后的datetime对象排序
sorted_month_cols = sorted(month_columns, key=lambda x: pd.to_datetime(x, format="%b %y"))

# 重新组织DataFrame的列:先保留Flavor列,再跟上排序后的月份列
df_sorted = df[["Flavor"] + sorted_month_cols]

补充说明

  • 这里的format="%b %y"是匹配你的列名格式:%b代表月份缩写(比如Feb、Jan),%y代表两位年份(比如18)
  • 即使遇到跨年份的情况(比如Dec 17和Jan 18),这个方法也能正确按时间先后排序,因为datetime对象会自动处理年份的优先级
  • 排序后你的列会变成Flavor, Jan 18, Feb 18, Mar 18的正确时间顺序

内容的提问来源于stack exchange,提问作者florence-y

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:47:37