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

如何用Pandas将指定JSON转为目标结构DataFrame?已尝试json_normalize失败

解决方案

你可以通过两步实现需求:先从JSON的f2字段提取列表生成基础DataFrame,再添加自定义列temp_col并填充对应字典值。

方法1:直接构造DataFrame(最直观)

import pandas as pd

data = {
 "f1": "test",
 "f2":[{"f3": 1, "f4": "f4_1" }, {"f3": 2, "f4": "f4_2" }] 
}

# 从f2的列表生成包含f3、f4的DataFrame
df = pd.DataFrame(data["f2"])
# 添加temp_col列,每行填充{"f1": "test"}
df["temp_col"] = [{"f1": data["f1"]}] * len(df)

方法2:正确使用json_normalize

你之前用json_normalize无效,大概率是没有指定record_path参数来指定要展开的嵌套数组。正确用法如下:

import pandas as pd

data = {
 "f1": "test",
 "f2":[{"f3": 1, "f4": "f4_1" }, {"f3": 2, "f4": "f4_2" }] 
}

# 指定record_path="f2",展开嵌套数组为行
df = pd.json_normalize(data, record_path="f2")
# 填充temp_col列,pandas会自动将单个字典广播到所有行
df["temp_col"] = {"f1": data["f1"]}

执行后得到的DataFrame结构与你需求一致:

f3     f4          temp_col
0   1  f4_1  {'f1': 'test'}
1   2  f4_2  {'f1': 'test'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:22:40