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

如何将指定结构的Python DataFrame转换为季度维度的宽表?

问题描述

现有如下结构的Python DataFrame:

State Feature       2020Q1  2020Q2 2020Q3   2020Q4.....2030Q4
AL    Population     100000 100020  100030  100040     100050
AL    InterestRate   1.5    1.5     1.5      1.6        1.6
AZ    Population     200001  200002 200003   200004..... 300002
AZ    InterestRate   2.0    2.0      2.0     2.0 ..........3.0

需要转换为如下目标格式:

State YearQuarter  Population     InterestRate   
AL     2020Q1      100000          1.5
AL     2020Q2      100020          1.5
AL     2020Q3      100030          1.5
AL     2020Q4      100040          1.6
.
.
AL     2030Q3      100050          1.6 
Python实现方法

借助pandas库的melt和pivot方法即可完成转换,具体步骤如下:

  1. 导入库并加载数据
import pandas as pd

# 构造示例数据(实际场景可替换为pd.read_csv/pd.read_excel等读取数据的方法)
data = {
    'State': ['AL', 'AL', 'AZ', 'AZ'],
    'Feature': ['Population', 'InterestRate', 'Population', 'InterestRate'],
    '2020Q1': [100000, 1.5, 200001, 2.0],
    '2020Q2': [100020, 1.5, 200002, 2.0],
    '2020Q3': [100030, 1.5, 200003, 2.0],
    '2020Q4': [100040, 1.6, 200004, 2.0],
    '2030Q4': [100050, 1.6, 300002, 3.0]
}
df = pd.DataFrame(data)
  1. 将季度列转为行(宽表转长表)
# 保留State、Feature作为标识列,把季度列转为YearQuarter,对应数值存入Value
melted_df = df.melt(id_vars=['State', 'Feature'], var_name='YearQuarter', value_name='Value')
  1. 将Feature转为列(长表转目标宽表)
# 以State和YearQuarter为索引,把Feature的不同取值转为列,对应填充Value
result_df = melted_df.pivot(index=['State', 'YearQuarter'], columns='Feature', values='Value').reset_index()
  1. 调整列顺序(匹配目标格式)
result_df = result_df[['State', 'YearQuarter', 'Population', 'InterestRate']]

执行完成后,result_df即为目标格式的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:39:25