如何用Pandas将嵌套JSON先拆分为多行再拆分为多列?
处理嵌套JSON数据展开为目标DataFrame的方法
问题场景
我有如下嵌套JSON数据:
sample = [ { "id": 1, "name": "Tiago", "activities": [ { "task_id": 1, "task_name": "Clean the house", "date": 1683687600000 }, { "task_id": 2, "task_name": "Play piano", "date": 1683687600000 } ] }, { "id": 2, "name": "Frank", "activities": [ { "task_id": 1, "task_name": "Walk with the dog", "date": 1683687600000 }, { "task_id": 2, "task_name": "Go to the gym", "date": 1683687600000 } ] }, ]
执行pd.DataFrame.from_records(sample)后,得到的DataFrame中activities列是嵌套的列表字典,无法直接使用:
id name activities 0 1 Tiago [{'task_id': 1, 'task_name': 'Clean the house'... 1 2 Frank [{'task_id': 1, 'task_name': 'Walk with the do...
需要将数据拆分为多行,并展开成如下格式:
id name task_id task_name date 0 1 Tiago 1 Clean the house 1683687600000 1 1 Tiago 2 Play piano 1683687600000 2 2 Frank 1 Walk with the dog 1683687600000 3 2 Frank 2 Go to the gym 1683687600000
解决方案
方法一:分步处理(拆分多行+展开列)
先通过explode拆分嵌套列表为多行,再用json_normalize展开字典为列:
import pandas as pd # 初始转换为DataFrame df = pd.DataFrame.from_records(sample) # 拆分activities列的列表为多行 df_exploded = df.explode('activities', ignore_index=True) # 展开activities中的字典为独立列,并和原表的id、name列合并 df_final = pd.concat([ df_exploded[['id', 'name']], pd.json_normalize(df_exploded['activities']) ], axis=1) print(df_final)
方法二:一步到位(直接用json_normalize参数)
利用pd.json_normalize的record_path指定嵌套数据路径,meta保留外层字段,无需中间步骤:
import pandas as pd df_final = pd.json_normalize( sample, record_path='activities', # 指定要展开的嵌套数组路径 meta=['id', 'name'] # 指定需要保留的外层字段 ) # 调整列顺序以匹配目标格式(可选) df_final = df_final[['id', 'name', 'task_id', 'task_name', 'date']] print(df_final)
两种方法都能得到目标格式的DataFrame,方法二更简洁高效。
内容的提问来源于stack exchange,提问作者Andre Araujo
相关产品推荐
相关产品推荐

