如何将含空值与嵌套JSON的列表转为指定格式的Pandas DataFrame?
解决方案
问题原因
直接使用pd.json_normalize(attach)处理时,外层列表的每个子列表会被当作单独的记录,导致生成的DataFrame以子列表的索引作为列名(如0、1等),而非JSON对象的键,因此不符合预期格式。
解决步骤
先预处理原始数据:
- 空的子列表转换为包含所有目标字段且值为
None的字典,对应一行全空数据; - 非空的子列表直接展开其中的每个JSON对象,每个对象对应一行数据;
- 最后用
pd.json_normalize处理整理后的字典列表。
完整代码示例
import pandas as pd # 原始数据 attach = [ [], [], [ {'id': 32, 'globalId': 'a73dec29-9431-4806-a4f7-0667872746ce', 'parentGlobalId': 'ad21cef5-cfa7-4e52-ab8f-8b5da30020af', 'name': 'IMG_9774.jpeg', 'contentType': 'image/jpeg', 'size': 157893, 'keywords': '', 'exifInfo': None}, {'id': 33, 'globalId': '0455db91-946e-4fae-8aab-0a4729219527', 'parentGlobalId': 'ad21cef5-cfa7-4e52-ab8f-8b5da30020af', 'name': 'IMG_9766.jpeg', 'contentType': 'image/jpeg', 'size': 160480, 'keywords': '', 'exifInfo': None}, {'id': 34, 'globalId': '4c036305-a1c5-4689-8640-1dc79aaf0358', 'parentGlobalId': 'ad21cef5-cfa7-4e52-ab8f-8b5da30020af', 'name': 'IMG_3870.jpeg', 'contentType': 'image/jpeg', 'size': 757939, 'keywords': '', 'exifInfo': None}, {'id': 35, 'globalId': '1868ac95-1830-45fb-8f15-975ef0e14338', 'parentGlobalId': 'ad21cef5-cfa7-4e52-ab8f-8b5da30020af', 'name': 'IMG_2357.jpeg', 'contentType': 'image/jpeg', 'size': 4500893, 'keywords': '', 'exifInfo': None} ], [] ] # 预处理数据 all_records = [] # 获取所有字段名(从第一个非空子列表提取) if any(sublist for sublist in attach): fields = next(sublist for sublist in attach if sublist)[0].keys() else: fields = [] for sublist in attach: if not sublist: # 空列表对应全None的记录 all_records.append({field: None for field in fields}) else: # 非空列表展开所有对象 all_records.extend(sublist) # 生成目标DataFrame df = pd.json_normalize(all_records) print(df)
输出结果
id globalId parentGlobalId name contentType size keywords exifInfo 0 None None None None None None None 1 None None None None None None None 2 32 a73dec29-9431-4806-a4f7-0667872746ce ad21cef5-cfa7-4e52-ab8f-8b5da30020af IMG_9774.jpeg image/jpeg 157893 None 3 33 0455db91-946e-4fae-8aab-0a4729219527 ad21cef5-cfa7-4e52-ab8f-8b5da30020af IMG_9766.jpeg image/jpeg 160480 None 4 34 4c036305-a1c5-4689-8640-1dc79aaf0358 ad21cef5-cfa7-4e52-ab8f-8b5da30020af IMG_3870.jpeg image/jpeg 757939 None 5 35 1868ac95-1830-45fb-8f15-975ef0e14338 ad21cef5-cfa7-4e52-ab8f-8b5da30020af IMG_2357.jpeg image/jpeg 4500893 None 6 None None None None None None None
内容的提问来源于stack exchange,提问作者Zac Stanley
相关产品推荐
相关产品推荐

