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

解决Yahoo Finance获取标普500公司高管数据的.iloc[0]越界错误

解决Yahoo Finance获取标普500公司高管数据时的索引越界问题

问题原因

你遇到的"Single positional indexer is out-of-bounds"错误,本质是部分标普500公司的Yahoo Finance数据里没有companyOfficers字段。当循环到这类公司时:

  • df0.loc[df0['Name'] == 'companyOfficers']会返回一个空的DataFrame
  • 此时执行df0['Value'].iloc[0],因为空数据没有第0行,直接触发索引越界错误

前60家公司刚好都有这个字段,所以运行正常;扩大到70家时,碰到了没有该字段的公司,就报错了。

修复方案

核心思路是先判断数据是否存在,再执行后续操作,同时简化代码逻辑,避免不必要的DataFrame转换:

修改后的完整代码

# 提取标普500公司列表
import pandas as pd
import yfinance as yf

table = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
sp500 = table[0]["Symbol"].tolist()

result_df = pd.DataFrame()

for symbol in sp500:
    stock = yf.Ticker(symbol)
    # 直接从info字典中获取高管数据,避免多余的DataFrame转换
    officers_data = stock.info.get('companyOfficers')
    
    # 检查数据是否存在且非空
    if officers_data and len(officers_data) > 0:
        # 取第一位高管数据,添加股票代码列
        officer_df = pd.DataFrame(officers_data).head(1)
        officer_df['Stock'] = symbol
        # 合并到结果表
        result_df = pd.concat([result_df, officer_df], axis=0)
    else:
        # 可选:打印缺失数据的公司,方便排查
        print(f"跳过 {symbol}:未获取到高管数据")

# 重置索引(可选)
result_df.reset_index(drop=True, inplace=True)

关键优化点

  1. 直接读取字段:用stock.info.get('companyOfficers')替代先转DataFrame再筛选,减少中间步骤,提升效率
  2. 空值判断:通过if officers_data and len(officers_data) > 0确保数据存在后再处理,避免索引越界
  3. 循环简化:直接遍历股票代码列表,比用range索引更直观
  4. 错误提示:添加打印语句,方便知道哪些公司没有数据

这个版本可以适配全部标普500公司,遇到缺失数据的公司会自动跳过,不会中断运行。

内容的提问来源于stack exchange,提问作者Nino.Ninov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:13:20