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

如何在Pandas中展平多级索引,使所有列与Date同级并将Date设为索引?

Fixing Multi-Level Index & Setting Date as Index for Yahoo Finance Data

Let's break down what's going wrong in your code and fix it step by step:

Two Key Issues in Your Current Code

  1. You didn't assign the result of set_index('Date') back to your DataFrame
    Pandas methods like set_index() return a new DataFrame by default—they don't modify the original object in place. So your data variable stayed unchanged after calling this line.
  2. Using to_records() is unnecessary
    Converting to a structured record array and back to a DataFrame is a roundabout way to handle the stacked data; we can clean this up with more straightforward pandas operations.

Corrected Code

First, make sure you import pandas (you missed this in your original snippet):

import pandas as pd
from pandas_datareader import data

Then process the data with cleaner, explicit steps:

stocks = ['GOOG', 'AAPL','MSFT']
# Fetch data from Yahoo Finance
df = data.DataReader(stocks,'yahoo')

# Stack the second level of column index (stock symbols) into row index
df_stacked = df.stack(level=1)
# Convert the multi-level row index into regular columns
df_stacked = df_stacked.reset_index()
# Rename the auto-generated 'level_1' column to 'Symbols'
df_stacked = df_stacked.rename(columns={'level_1': 'Symbols'})
# Set Date as the index, and assign back to update the DataFrame
df_final = df_stacked.set_index('Date')

Or use chained operations for brevity:

df_final = (data.DataReader(stocks,'yahoo')
            .stack(level=1)
            .reset_index()
            .rename(columns={'level_1': 'Symbols'})
            .set_index('Date'))

Verify the Result

Check the columns and index to confirm everything is as expected:

print(df_final.columns)
# Output: Index(['Symbols', 'Adj Close', 'Close', 'High', 'Low', 'Open', 'Volume'], dtype='object')

print(df_final.index.name)
# Output: 'Date'

How This Works

  • stack(level=1) moves the stock symbols (second level of the original column index) into the row index, creating a multi-level index of (Date, Symbols).
  • reset_index() converts both levels of the row index into regular columns (Date and the auto-named level_1 for symbols).
  • rename() fixes the default column name for symbols to match your desired structure.
  • set_index('Date') makes Date the primary index, and assigning the result ensures your DataFrame reflects this change.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:52:38