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

使用pandas读取API JSON数据报错:Mixing dicts with non-Series...如何解决?

解决Pandas read_json报错“Mixing dicts with non-Series may lead to ambiguous ordering”

这个错误的根源是API返回的JSON结构嵌套复杂,直接用read_json解析时,字典与非序列类型数据混合,导致Pandas无法确定数据排序逻辑。以下是两种可行的解决方法:

方法1:手动解析JSON结构(推荐)

先获取原始JSON数据,提取出核心的表格型数据后再转为DataFrame,能精准适配复杂嵌套结构:

import pandas as pd
import requests

# 获取API数据并解析为字典
response = requests.get('https://api.cbs.gov.il/index/data/price?id=120010&format=json&download=false')
json_data = response.json()

# 定位有效数据字段(根据API返回的实际结构调整键名,示例为核心数据所在路径)
target_data = json_data['data']

# 转换为DataFrame并保存
df = pd.DataFrame(target_data)
df.to_excel('Data.xlsx', index=False)

方法2:指定orient参数适配格式

如果不想额外引入requests,可以尝试为read_json指定orient参数,匹配JSON的结构类型(常见取值有'records'、'columns'、'index'等):

import pandas as pd

# 根据JSON结构选择合适的orient值,示例使用records
df = pd.read_json('https://api.cbs.gov.il/index/data/price?id=120010&format=json&download=false', orient='records')
df.to_excel('Data.xlsx', index=False)

注:这种方法对结构特别复杂的JSON兼容性较差,优先推荐方法1。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:34:56