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

如何用Pandas将指定嵌套JSON解析为目标格式的DataFrame?

嗨,我来帮你搞定这个嵌套JSON转DataFrame的问题!

你已经用pd.read_json("json.json", lines=True)做对了第一步——因为你的文件是每行一个独立JSON对象,lines=True能正确读取它们,但读出来的DataFrame里只有一列SeriousDlqin2yrs,每个单元格都是嵌套的字典,这就是你后续操作卡壳的原因。

其实Pandas有个专门处理嵌套JSON的工具pd.json_normalize,用它就能一步到位展开你要的结构,比apply高效多了,具体代码如下:

import pandas as pd
import json

# 方法一:先读取每行JSON再解析
with open("json.json", "r") as f:
    json_data = [json.loads(line.strip()) for line in f]

df = pd.json_normalize(json_data)

# 方法二:基于你已有的read_json结果直接处理
predictions = pd.read_json("json.json", lines=True)
df = pd.json_normalize(predictions["SeriousDlqin2yrs"])

运行后你会得到完全符合预期的DataFrame:

predictionprediction_probs.0prediction_probs.1
00.950.04
00.960.03

如果你非要用apply的方式(不推荐,效率偏低),也可以这样调整:

predictions = pd.read_json("json.json", lines=True)
df = pd.concat(
    predictions.apply(lambda row: pd.DataFrame(row["SeriousDlqin2yrs"], index=[row.name]), axis=1)
)

本质是把每行的嵌套字典转换成一个小DataFrame,再用pd.concat把它们拼接成完整的结构,但显然json_normalize是更优雅的解决方案~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:02:42