如何将指定结构的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方法即可完成转换,具体步骤如下:
- 导入库并加载数据
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)
- 将季度列转为行(宽表转长表)
# 保留State、Feature作为标识列,把季度列转为YearQuarter,对应数值存入Value melted_df = df.melt(id_vars=['State', 'Feature'], var_name='YearQuarter', value_name='Value')
- 将Feature转为列(长表转目标宽表)
# 以State和YearQuarter为索引,把Feature的不同取值转为列,对应填充Value result_df = melted_df.pivot(index=['State', 'YearQuarter'], columns='Feature', values='Value').reset_index()
- 调整列顺序(匹配目标格式)
result_df = result_df[['State', 'YearQuarter', 'Population', 'InterestRate']]
执行完成后,result_df即为目标格式的DataFrame。
内容的提问来源于stack exchange,提问作者K Jayabalan
相关产品推荐
相关产品推荐

