如何在Yahoo Finance API中访问并操作Pandas DataFrame行数据
解决Yahoo Finance API earnings_history的ValueError及数据提取问题
问题分析
调用yahoo_stock_obj.earnings_history.iloc[0]触发ValueError: The truth value of a DataFrame is ambiguous,大概率是因为earnings_history并非标准的扁平DataFrame,可能存在嵌套结构(比如部分列或行是子DataFrame),或是yfinance版本差异导致返回数据格式异常。
解决方案
1. 标准化数据结构
先将earnings_history转换为扁平的DataFrame,消除嵌套结构的干扰:
import yfinance import pandas as pd # 初始化Ticker对象 yahoo_stock_obj = yfinance.Ticker('HD') # 获取盈利历史数据 earnings_data = yahoo_stock_obj.earnings_history # 处理嵌套结构:如果返回的是Series则合并为统一DataFrame if isinstance(earnings_data, pd.Series): earnings_df = pd.concat(earnings_data.tolist(), ignore_index=True) else: earnings_df = earnings_data.copy() # 清理关键字段的缺失值,避免后续提取出错 earnings_df = earnings_df.dropna(subset=['Earnings Date', 'EPS Estimate', 'Reported EPS', 'Surprise(%)'])
2. 遍历提取目标字段
以下两种方式均可实现数据提取,按需选择:
方法一:用iterrows()逐行遍历
for _, row in earnings_df.iterrows(): # 提取指定字段 earnings_date = row['Earnings Date'] eps_estimate = row['EPS Estimate'] reported_eps = row['Reported EPS'] surprise_percent = row['Surprise(%)'] # 此处替换为存入数据库的逻辑 print(f"日期: {earnings_date}, 预期EPS: {eps_estimate}, 实际EPS: {reported_eps}, 惊喜率: {surprise_percent}")
方法二:转为字典列表批量处理
# 仅保留需要的列,转换为字典列表(每个字典对应一行数据) earnings_records = earnings_df[['Earnings Date', 'EPS Estimate', 'Reported EPS', 'Surprise(%)']].to_dict('records') for record in earnings_records: # 直接从字典中取值 print(f"日期: {record['Earnings Date']}, 预期EPS: {record['EPS Estimate']}, 实际EPS: {record['Reported EPS']}, 惊喜率: {record['Surprise(%)']}") # 执行存入数据库操作
3. 验证首行数据
标准化后可正常访问首行,不会触发原错误:
# 获取并打印首行数据 first_row = earnings_df.iloc[0] print(first_row)
内容的提问来源于stack exchange,提问作者codyc4321
相关产品推荐
相关产品推荐

