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

如何在Pandas中将日期列名转为指定格式并按降序排序?

解决日期列名降序排列问题

问题出在你直接把日期转成字符串后,透视表的列会按字符串字典序排序,而非实际的日期先后顺序。要实现日期列按降序排列,需要先基于datetime类型对日期排序,再用排序后的字符串列表调整透视表的列顺序。

完整代码实现

import pandas as pd

# 加载原始数据
data = [
    ["Server1", "wan1", 100, 80, "ATT", "2024-05-09"],
    ["Server1", "wan1", 100, 50, "Sprint", "2024-06-21"],
    ["Server1", "wan1", 100, 30, "Verizon", "2024-07-01"],
    ["Server2", "wan1", 100, 90, "ATT", "2024-05-01"],
    ["Server2", "wan1", 100, 88, "Sprint", "2024-06-02"],
    ["Server2", "wan1", 100, 22, "Verizon", "2024-07-19"]
]
df = pd.DataFrame(data, columns=["Node", "Interface", "Speed", "Band_In", "carrier", "Date"])

# 1. 保留datetime格式的日期用于排序,同时生成目标格式的字符串
df['Date_dt'] = pd.to_datetime(df['Date'])
# 生成「1-May」「21-Jun」这类格式(Windows系统把%-d换成%#d)
df['Date_str'] = df['Date_dt'].dt.strftime('%-d-%B')

# 2. 计算带宽使用率(和你原代码逻辑一致)
df['is'] = df['Band_In'] / df['Speed'] * 100

# 3. 生成透视表,包含Speed、Band_In列(匹配你期望的输出结构)
pivot_df = df.pivot_table(
    index=['Node', 'Interface', 'Speed', 'Band_In', 'carrier'],
    columns='Date_str',
    values='is',
    aggfunc='first'  # 每个分组对应唯一值,用first即可
).reset_index()

# 4. 基于datetime降序获取排序后的日期字符串列表
sorted_date_cols = df.sort_values('Date_dt', ascending=False)['Date_str'].unique()

# 5. 重新调整透视表的列顺序
final_df = pivot_df[['Node', 'Interface', 'Speed', 'Band_In', 'carrier'] + list(sorted_date_cols)]

print(final_df)

关键逻辑说明

  • 单独保留Date_dt列(datetime类型)用于排序,避免字符串排序的偏差;
  • 透视表生成后,用sort_values('Date_dt', ascending=False)得到降序的日期字符串序列,再重新排列列顺序;
  • 针对日期格式的细节:%-d用于去掉日期前的零(如09→9),%B用于月份全称(May→May,Jul→July),Windows系统需替换为%#d。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:25:16