在for循环中连接json数据

问题描述 投票:0回答:1

我有很多股票行情,我需要获取完整的报价信息。我使用了

for
循环来遍历代码,并在每个代码上调用
requests.get()
。我需要将股票报价附加到主
DataFrame()
,并使用
concat()
附加每个股票。

df = pd.DataFrame()
for symbol in get_earnings.head(5):
    url = f'https://financialmodelingprep.com/api/v3/quote/{symbol}?apikey={api_key_3}'
    data = requests.get(url)
    response = data.json()
    dx = pd.DataFrame(response)
    df = pd.concat([df, dx], axis=0, ignore_index=True)
    if len(df) > 1:
        df.to_csv('data/latestEarnings.csv')

我收到此错误

ValueError: If using all scalar values, you must pass an index

每个股票代码的

response = data.json()
的输出,我需要将其附加到主
DataFrame()

[{'symbol': 'RSKIA', 'name': 'George Risk Industries, Inc.', 'price': 13.1, 'changesPercentage': 4.8839, 'change': 0.61, 'dayLow': 12.49, 'dayHigh': 14.1, 'yearHigh': 14.1, 'yearLow': 9.81, 'marketCap': 64191703, 'priceAvg50': 12.2656, 'priceAvg200': 11.74125, 'exchange': 'PNK', 'volume': 6498, 'avgVolume': 406, 'open': 12.49, 'previousClose': 12.49, 'eps': 1.35, 'pe': 9.7, 'earningsAnnouncement': '2024-03-15T10:59:00.000+0000', 'sharesOutstanding': 4900130, 'timestamp': 1710781859}]
json pandas python-requests
1个回答
0
投票

尝试改变:

dx = pd.DataFrame(response)

至:

dx = pd.DataFrame([response])

另请注意,最后两行的缩进错误。它们应该在循环之外。

© www.soinside.com 2019 - 2024. All rights reserved.