如何拆分Pandas中多股票多层表头DataFrame为独立数据表
Solution to Split Multi-Index Stock DataFrame
Hey there! No worries, splitting that multi-index DataFrame from stooq into separate DataFrames for each stock is totally straightforward. Here's exactly how you can get the output you're looking for:
Step-by-Step Solution
First, let's recap your original data fetching code, then add the splitting logic using pandas' built-in xs() method (short for cross-section), which is perfect for working with multi-index columns.
import datetime as dt import pandas as pd import pandas_datareader.data as web pd.set_option('display.max_columns', 500) stocks = ["1.HK", "2.HK"] start_time = dt.datetime(2022, 7, 1) end_time = dt.datetime.now().date().isoformat() # Fetch the multi-index data from stooq df = web.DataReader(stocks, 'stooq', start_time, end_time) # Split into individual DataFrames for each stock # xs() extracts all columns for the specified symbol from the 'Symbols' level df_1HK = df.xs('1.HK', axis=1, level='Symbols').sort_index() df_2HK = df.xs('2.HK', axis=1, level='Symbols').sort_index() # Print the results to verify print("df_1HK:") print(df_1HK) print("\ndf_2HK:") print(df_2HK)
What This Does
- The
xs('1.HK', axis=1, level='Symbols')call targets the second level of your column index (Symbols) and pulls all rows/columns associated with "1.HK"—this gives you exactly the Close, High, Low, Open, and Volume columns for that stock. sort_index()reorders the dates from oldest to newest, matching the format you showed in your desired output (since stooq returns data with the most recent date first by default).
Example Output
Running this code will produce df_1HK and df_2HK structured exactly as you requested:
- Each uses
Dateas the index - Columns are named
Close,High,Low,Open,Volume - All data is filtered to the respective stock
内容的提问来源于stack exchange,提问作者Marcin
相关产品推荐
相关产品推荐

