如何将Pandas多级索引表头转换为单索引并调整结构
调整多级索引DataFrame结构的解决方案
原始数据场景
用户通过以下代码获取股票行情数据:
import pandas as pd import yfinance as yf pd.set_option('display.max_columns', None) symbols=["A","AA"] df = yf.download(symbols, period='7d') print(df.head())
得到的是多级列索引的DataFrame,结构如下:
Adj Close Close A AA A AA Date 2023-02-28 00:00:00-05:00 141.970001 48.851852 141.970001 48.939999 2023-03-01 00:00:00-05:00 137.509995 51.556973 137.509995 51.650002 2023-03-02 00:00:00-05:00 141.669998 53.593296 141.669998 53.689999 2023-03-03 00:00:00-05:00 143.929993 55.420002 143.929993 55.520000 2023-03-06 00:00:00-05:00 143.229996 53.689999 143.229996 53.689999 High Low A AA A AA Date 2023-02-28 00:00:00-05:00 143.380005 50.040001 141.389999 47.799999 2023-03-01 00:00:00-05:00 139.990005 52.959999 136.250000 50.529999 2023-03-02 00:00:00-05:00 141.720001 53.709999 136.080002 50.049999 2023-03-03 00:00:00-05:00 144.440002 55.740002 141.979996 53.700001 2023-03-06 00:00:00-05:00 145.440002 54.900002 142.679993 53.380001 Open Volume A AA A AA Date 2023-02-28 00:00:00-05:00 141.750000 48.250000 2342500 3871400 2023-03-01 00:00:00-05:00 138.580002 51.290001 3132800 7599600 2023-03-02 00:00:00-05:00 136.300003 50.189999 1879200 6467900 2023-03-03 00:00:00-05:00 142.539993 54.330002 1147800 6158800 2023-03-06 00:00:00-05:00 143.350006 54.009998 1153600 5129900
需求说明
需要将上述结构调整为:把表头中的股票代码(A、AA)提取为新的symbol列,表头仅保留行情指标(Adj Close、Close等),最终每行对应单只股票的单日数据。
解决方案代码
可以通过Pandas的stack()和reset_index()方法实现:
# 调整多级列索引,将股票代码层转为行 df_reshaped = df.stack(level=1).reset_index() # 重命名股票代码对应的列名为symbol df_reshaped.rename(columns={'level_1': 'symbol'}, inplace=True) # 查看调整后的结果 print(df_reshaped.head())
调整后的数据结构
运行上述代码后,得到的DataFrame结构如下:
Date symbol Adj Close Close High Low Open Volume 0 2023-02-28 00:00:00-05:00 A 141.970001 141.970001 143.380005 141.389999 141.750000 2342500 1 2023-02-28 00:00:00-05:00 AA 48.851852 48.939999 50.040001 47.799999 48.250000 3871400 2 2023-03-01 00:00:00-05:00 A 137.509995 137.509995 139.990005 136.250000 138.580002 3132800 3 2023-03-01 00:00:00-05:00 AA 51.556973 51.650002 52.959999 50.529999 51.290001 7599600 4 2023-03-02 00:00:00-05:00 A 141.669998 141.669998 141.720001 136.080002 136.300003 1879200
代码解释
stack(level=1):将多级列索引的第1层(股票代码A、AA)转换为行索引的一部分,实现“宽表转长表”的效果。reset_index():将原来的行索引(Date)和新生成的股票代码索引转为普通列。rename(columns={'level_1': 'symbol'}):把默认生成的level_1列名改为更直观的symbol。
内容的提问来源于stack exchange,提问作者Marcixen
相关产品推荐
相关产品推荐

