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

如何将DataFrame从长格式重塑为宽格式并按时间顺序排列日期列

解决方法

核心问题分析

你遇到的日期列按字母顺序排列的问题,本质是如果将日期以字符串格式处理,会按字母排序;而正确转为datetime类型后,pandas会自动按时间顺序排列。可能你在转换datetime时格式指定有误,或者后续重命名列时打乱了原有顺序。

步骤1:正确转换日期格式

首先确保Month列被正确解析为datetime类型,指定格式%b-%y(缩写月份+两位年份):

import pandas as pd

# 假设你的数据框是CF
CF['Month'] = pd.to_datetime(CF['Month'], format='%b-%y')

步骤2:直接使用pivot_table完成聚合与重塑

无需先groupby再pivot,pivot_table可以直接完成分组求和与宽格式转换,更高效:

pivot = CF.pivot_table(
    index=['Type', 'Subtype'],
    columns='Month',
    values='Amount',
    aggfunc='sum',
    fill_value=0
)

此时列已经是按时间顺序排列的datetime类型。

步骤3:重命名列为目标格式(可选)

如果需要将列名显示为Dec-20这类格式,直接对datetime列进行格式化,保留原有顺序:

pivot.columns = pivot.columns.strftime('%b-%y')
# 可选:移除列名的标题(如目标输出中没有"Month"列标题)
pivot.columns.name = None

完整代码示例

import pandas as pd

# 模拟你的数据
data = {
    'Type': ['A', 'A', 'A', 'A', 'C'],
    'Subtype': ['a', 'b', 'a', 'c', 'a'],
    'Month': ['Jan-21', 'Feb-21', 'Jan-21', 'Mar-21', 'Dec-20'],
    'Amount': [7, 9, 8, 2, 7]
}
CF = pd.DataFrame(data)

# 转换日期格式
CF['Month'] = pd.to_datetime(CF['Month'], format='%b-%y')

# 生成宽格式表
pivot = CF.pivot_table(
    index=['Type', 'Subtype'],
    columns='Month',
    values='Amount',
    aggfunc='sum',
    fill_value=0
)

# 重命名列
pivot.columns = pivot.columns.strftime('%b-%y')
pivot.columns.name = None

print(pivot)

输出结果

Dec-20  Jan-21  Feb-21  Mar-21
Type Subtype                               
A    a           0      15       0       0
     b           0       0       9       0
     c           0       0       0       2
C    a           7       0       0       0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:27:29