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

循环获取股票行情并concat拼接DataFrame时遇ValueError错误求助

问题解决:合并股票行情DataFrame时触发ValueError错误

错误原因

你的代码报错ValueError: If using all scalar values, you must pass an index,本质是某个股票代码的API返回数据不符合预期格式——可能是请求失败返回了错误信息字典、空数据,或者非列表结构的内容,导致pd.DataFrame(response)无法正常创建DataFrame(pandas无法将纯标量值集合转为DataFrame,除非指定索引)。

修复方案及优化代码

针对这个问题,我们需要在代码中增加数据有效性校验和异常捕获,确保只有符合格式的数据才会被合并,同时避免单个请求失败导致整个循环中断。修改后的代码如下:

import pandas as pd
import requests

df = pd.DataFrame()
# 遍历前5个股票代码
for symbol in get_earnings.head(5):
    url = f'https://financialmodelingprep.com/api/v3/quote/{symbol}?apikey={api_key_3}'
    try:
        # 发送请求并检查HTTP状态
        data = requests.get(url)
        data.raise_for_status()
        # 解析返回的JSON数据
        response = data.json()
        # 校验数据格式:必须是非空列表
        if isinstance(response, list) and len(response) > 0:
            dx = pd.DataFrame(response)
            df = pd.concat([df, dx], axis=0, ignore_index=True)
    except Exception as e:
        # 打印错误信息,不中断循环
        print(f"处理股票代码 {symbol} 时出错: {e}")

# 循环结束后统一保存CSV,避免重复IO操作
if not df.empty:
    df.to_csv('data/latestEarnings.csv', index=False)

关键修改点说明

  • 异常捕获:用try-except块包裹请求和数据处理逻辑,捕获网络错误、API报错等异常,保证单个股票处理失败时,循环能继续执行其他股票。
  • HTTP状态校验:data.raise_for_status()会在请求返回4xx/5xx错误时抛出异常,及时发现无效请求(比如股票代码不存在、API密钥错误)。
  • 数据格式校验:通过isinstance(response, list) and len(response) > 0确保返回的是预期的非空列表结构,避免创建DataFrame时触发格式错误。
  • 优化CSV写入:把保存CSV的操作移到循环外部,减少重复的磁盘写入操作,提升效率,同时避免多次写入重复数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:46:23