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

如何从json_normalize中间结果生成自定义列结构的Pandas DataFrame?

把嵌套JSON转换为指定结构的Pandas DataFrame

你已经通过pd.json_normalize生成了包含冗余字段的中间DataFrame,现在要把它转成以custom_fields的name为列、display_value为对应值,同时保留原数据name和due_on的目标结构,按以下步骤操作即可:

步骤1:过滤冗余字段

先从中间DataFrame里只保留需要的字段,去掉其他没用的:

import pandas as pd

# 假设你的中间DataFrame是df
filtered_df = df[['name', 'due_on', '_name', '_display_value']]

步骤2:重塑数据结构

用pivot方法把_name里的内容转成列,_display_value作为对应列的值,最后重置索引并清理列名:

# 重塑数据
target_df = filtered_df.pivot(
    index=['name', 'due_on'],
    columns='_name',
    values='_display_value'
).reset_index()

# 去掉列名的层级标签
target_df.columns.name = None

执行后得到的target_df就是你想要的结构:

namedue_onInputsT-Minus
General Information2023-01-25null54

额外:直接从原始JSON生成目标结构(跳过中间DataFrame)

如果不想生成中间DataFrame,也可以直接处理原始JSON数据,一步到位:

# 原始JSON数据(假设已存入test变量)
test = {"data": [{"gid": "1203715497540179","completed": False,"custom_fields": [{"gid": "1203887422469746","enabled": True,"name": "Inputs","description": "","display_value": None,"resource_subtype": "text","resource_type": "custom_field","text_value": None,"type": "text"},{"gid": "1126427465960522","enabled": False,"name": "T-Minus","description": "","display_value": "54","resource_subtype": "text","resource_type": "custom_field","text_value": "54","type": "text"}],"due_on": "2023-01-25","name": "General Information"}]}

# 拆分提取基础字段和自定义字段
df_base = pd.json_normalize(test['data'], meta=['name', 'due_on'])
df_custom = pd.json_normalize(test['data'], record_path='custom_fields', meta=['name'], record_prefix='cf_')

# 合并并重塑结构
df_custom_pivot = df_custom.pivot(index='name', columns='cf_name', values='cf_display_value').reset_index()
target_df = pd.merge(df_base[['name', 'due_on']], df_custom_pivot, on='name').drop_duplicates()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:47:30