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

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_index call (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

  1. List Collection: We use all_balance_sheets to store each ticker's DataFrame as we fetch it—this is the simplest way to prepare for concatenation compared to a dictionary.
  2. 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 prefer date and ticker as regular columns instead, just remove this line entirely.
  3. Smart Concatenation: pd.concat() stacks all DataFrames vertically. Since different tickers might have slightly different balance sheet items (like capitalSurplus for MU but not AAPL), pandas automatically fills missing values with NaN for columns that don't exist for a particular ticker.

Example Output Preview

Your unified DataFrame will look something like this (abbreviated):

datetickeraccountsPayablecashcommonStockcapitalSurplustotalLiab...
2019-12-28AAPL451110000003977100000045972000000NaN251087000000...
2019-09-28AAPL462360000004884400000045174000000NaN248028000000...
2019-12-31GOOG55610000001849800000050552000000NaN74467000000...
2019-11-28MU18790000006969000000NaN842800000013051000000...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:27:26