如何从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就是你想要的结构:
| name | due_on | Inputs | T-Minus |
|---|---|---|---|
| General Information | 2023-01-25 | null | 54 |
额外:直接从原始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
相关产品推荐
相关产品推荐

