Pandas多DataFrame合并问题:如何合并多只股票财报数据为单个DataFrame
Solution to Merge Quarterly Balance Sheets into a Single DataFrame
Got it, let's get those separate ticker DataFrames merged into one unified table. Here's how to adjust your code step by step:
Key Changes Needed
- Instead of storing each DataFrame in a dictionary, we'll collect all of them in a list (much easier for merging)
- Fix a small bug in the
set_indexcall (you need to pass a list of columns for a multi-index) - Use
pd.concat()to combine all DataFrames, handling any column differences between tickers automatically
Modified Code
import pandas as pd from yahoo_fin import YahooFinancials # Assuming you're using the yahoo-fin package def financefetch(ticker): yahoo_financials = YahooFinancials(ticker) balance_sheet_data_qt = yahoo_financials.get_financial_stmts('quarterly', 'balance') dataframe_entries = list() for result in balance_sheet_data_qt.get('balanceSheetHistoryQuarterly').get(ticker): extracted_date = list(result)[0] extracted_ticker = ticker dataframe_row = list(result.values())[0] dataframe_row['date'] = extracted_date dataframe_row['ticker'] = extracted_ticker dataframe_entries.append(dataframe_row) # Fix: Pass a list to set_index for a proper multi-index (date + ticker) df = pd.DataFrame(dataframe_entries).set_index(['date', 'ticker']) return df # Collect all individual DataFrames in a list instead of a dictionary all_balance_sheets = [] tickerlist = ['AAPL','GOOG', 'MU'] for ticker in tickerlist: df_single = financefetch(ticker) all_balance_sheets.append(df_single) # Merge all DataFrames into one unified table unified_df = pd.concat(all_balance_sheets, axis=0, sort=False) # Optional: Print the merged result to verify print(unified_df)
What This Does
- List Collection: We use
all_balance_sheetsto store each ticker's DataFrame as we fetch it—this is the simplest way to prepare for concatenation compared to a dictionary. - Fixed Multi-Index: The
set_index(['date', 'ticker'])correctly creates a multi-index, making it easy to filter data by ticker or date later. If you preferdateandtickeras regular columns instead, just remove this line entirely. - Smart Concatenation:
pd.concat()stacks all DataFrames vertically. Since different tickers might have slightly different balance sheet items (likecapitalSurplusfor MU but not AAPL), pandas automatically fills missing values withNaNfor columns that don't exist for a particular ticker.
Example Output Preview
Your unified DataFrame will look something like this (abbreviated):
| date | ticker | accountsPayable | cash | commonStock | capitalSurplus | totalLiab | ... |
|---|---|---|---|---|---|---|---|
| 2019-12-28 | AAPL | 45111000000 | 39771000000 | 45972000000 | NaN | 251087000000 | ... |
| 2019-09-28 | AAPL | 46236000000 | 48844000000 | 45174000000 | NaN | 248028000000 | ... |
| 2019-12-31 | GOOG | 5561000000 | 18498000000 | 50552000000 | NaN | 74467000000 | ... |
| 2019-11-28 | MU | 1879000000 | 6969000000 | NaN | 8428000000 | 13051000000 | ... |
内容的提问来源于stack exchange,提问作者windy_city_sp500
相关产品推荐
相关产品推荐

