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

API返回JSON列表转Pandas DataFrame时遇索引错误求助

问题解决:列表索引错误导致无法转换为DataFrame

问题根源

API返回的数据是外层为列表的结构(type(respuesta)显示为List),里面包含一个字典。你直接用respuesta['priceData']试图索引列表,而列表只能用整数/切片索引,不能用字符串键,因此触发list indices must be integers or slices, not str错误。

修正代码

基础版:仅转换priceData数据

直接从列表中取出字典元素,再提取priceData列表传入pd.json_normalize:

import pandas as pd

respuesta = requestResponse.json()
# 取列表中的第一个(也是唯一的)字典元素,再获取priceData
price_data = respuesta[0]['priceData']
# 转换为DataFrame
df = pd.json_normalize(price_data)

进阶版:保留上层字段(ticker、baseCurrency等)

如果需要把外层的ticker、baseCurrency等字段也保留到DataFrame中,可以这样做:

import pandas as pd

respuesta = requestResponse.json()
top_info = respuesta[0]
price_data = top_info['priceData']

# 转换priceData并关联上层字段
df = pd.json_normalize(price_data)
df['ticker'] = top_info['ticker']
df['baseCurrency'] = top_info['baseCurrency']
df['quoteCurrency'] = top_info['quoteCurrency']

或者使用json_normalize的meta参数直接关联:

df = pd.json_normalize(
    respuesta[0]['priceData'],
    meta=[['..', 'ticker'], ['..', 'baseCurrency'], ['..', 'quoteCurrency']]
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:47:10