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

使用Pandas导入JSON遇ValueError数组长度不一致问题求助

解决Pandas读取JSON时的ValueError: All arrays must be the same length问题

这个错误的核心原因是你要读取的JSON数据中,不同字段对应的数组长度不一致,而Pandas默认要求生成的DataFrame每一列的长度必须相同。以下是几种实用的解决方法:

方法1:先加载为Python对象再转置处理

先把JSON文件读取成原生的Python字典,再通过转置的方式让Pandas自动用NaN填充缺失值:

import pandas as pd
import json

# 读取JSON文件为Python字典
with open('/Users/kallesova/downloads/graphjunction/graph.json', 'r') as f:
    raw_data = json.load(f)

# 转置生成DataFrame,缺失值自动补NaN
df = pd.DataFrame.from_dict(raw_data, orient='index').T
print(df.to_string())

方法2:使用json_normalize处理嵌套JSON

如果你的JSON是嵌套结构(比如包含多层对象),用json_normalize可以更灵活地展开嵌套字段,同时处理长度不一致的情况:

import pandas as pd
import json

with open('/Users/kallesova/downloads/graphjunction/graph.json', 'r') as f:
    raw_data = json.load(f)

# 展开嵌套结构生成DataFrame
df = pd.json_normalize(raw_data)
print(df.to_string())

方法3:用explode展开数组字段

如果JSON里的对象包含长度不一的数组字段,需要把数组元素拆成单独行,可以用explode方法:

import pandas as pd
import json

with open('/Users/kallesova/downloads/graphjunction/graph.json', 'r') as f:
    raw_data = json.load(f)

# 将指定数组字段展开为多行
df = pd.DataFrame(raw_data).explode(['字段1', '字段2'], ignore_index=True)
print(df.to_string())

额外提示

在处理前可以先打印raw_data查看JSON的具体结构,这样能快速判断哪种方法更适合你的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:25:24