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

无法将JSON数据加载至Pandas DataFrame,报“All arrays must be of the same length”错误

解决JSON转Pandas DataFrame的长度不匹配问题

直接用pd.read_json读取API返回的完整JSON会报错,因为返回的JSON结构包含多个长度不一致的字段(比如元数据、记录列表)。正确的做法是先解析JSON,提取出包含有效数据的部分再转成DataFrame:

修改后的代码:

import json
import requests
import pandas as pd  # 补充导入pandas库

responseGBP = requests.get("https://public.opendatasoft.com/api/records/1.0/search/?dataset=euro-exchange-rates&sort=date&facet=currency&rows=30&facet=date&q=date:[2020-12-01+TO+2020-12-31]&refine.currency=GBP")
# 将响应内容解析为Python字典
response_dict = json.loads(responseGBP.content.decode("utf-8"))
# 提取records列表中每个元素的fields字段,这是实际的汇率数据
df = pd.DataFrame([record['fields'] for record in response_dict['records']])
print(df)

原因说明

该API返回的JSON结构外层包含nhits、parameters、records等多个字段,其中只有records是包含每日汇率数据的列表,每个列表元素里的fields字段才是我们需要的日期、汇率值等具体信息。直接读取整个JSON时,不同字段的结构类型(单个对象 vs 列表)导致长度不匹配,触发报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:01:04