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

如何将年月格式的Pandas DataFrame转换为按年分行的多列结构

Pandas 长格式转宽格式(年份为行、月份为列)

步骤说明

假设原始DataFrame包含两列:month_year(格式为「月份-年份」)和value(对应数值),按以下步骤转换:

  1. 拆分月份与年份列
    使用str.split拆分month_year列,分离出独立的月份和年份字段,并将年份转为整数类型。

  2. 指定月份排序规则
    避免月份按字母顺序排列(如April排在January前),将月份列转为分类类型并指定正确的顺序。

  3. 转置为宽格式
    使用pivot方法将数据重构为以年份为行、月份为列的结构,最后重置索引让年份成为普通列。


完整代码示例

import pandas as pd

# 1. 构造示例数据(替换为你的实际数据)
data = [
    ['January-2021', 0.294],
    ['February-2021', 0.252],
    ['March-2021', 0.199],
    ['January-2022', 0.384],
    ['February-2022', 0.333],
    ['March-2022', 0.271]
]
df = pd.DataFrame(data, columns=['month_year', 'value'])

# 2. 拆分月份和年份
df[['month', 'year']] = df['month_year'].str.split('-', expand=True)
df['year'] = df['year'].astype(int)

# 3. 设置月份的正确顺序
month_order = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
]
df['month'] = pd.Categorical(df['month'], categories=month_order, ordered=True)

# 4. 转置为目标格式
result_df = df.pivot(index='year', columns='month', values='value').reset_index()
result_df.columns.name = None  # 移除列索引的名称

# 可选:输出为CSV文件
# result_df.to_csv('output.csv', index=False)

print(result_df)

输出结果

year  January  February  March
0  2021    0.294     0.252  0.199
1  2022    0.384     0.333  0.271

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:45:38