如何在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
- You didn't assign the result of
set_index('Date')back to your DataFrame
Pandas methods likeset_index()return a new DataFrame by default—they don't modify the original object in place. So yourdatavariable stayed unchanged after calling this line. - 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-namedlevel_1for 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
相关产品推荐
相关产品推荐

