使用json_normalize提取嵌套JSON的vehicles.type字段报错求助
解决json_normalize提取vehicles.type的报错问题
错误原因
你在meta参数中使用['vehicles']['type']的写法是错误的——vehicles是一个包含多个对象的列表字段,无法直接通过字符串索引提取内部属性,这就是触发list indices must be integers or slices, not str报错的原因。
解决方案
方案1:提取所有车辆类型为列表(保留原关联结构)
先展开casualties并保留vehicles列表,再通过apply提取所有车辆类型:
import json import pandas as pd # 加载数据 with open('/Users/samappleton/Documents/Python/Project/api_response_2023-01-31-13:22.json','r') as f: data = json.loads(f.read()) # 展开casualties,保留vehicles作为元数据字段 df = pd.json_normalize( data, record_path=['casualties'], meta=['id', 'lat', 'lon', 'location', 'date', 'severity', 'borough', 'vehicles'], record_prefix='casualties.' ) # 从vehicles列表中提取所有type值,生成新列 df['vehicles.types'] = df['vehicles'].apply(lambda x: [v['type'] for v in x]) # 可选:如果需要拆分每个车辆类型为单独行(会复制casualties行数据) # df_exploded = df.explode('vehicles.types', ignore_index=True) print(df)
方案2:生成伤亡人员与车辆类型的笛卡尔积行
如果需要每个伤亡人员和对应事故的每辆车辆都生成一行数据,可以分两次使用json_normalize:
import json import pandas as pd # 加载数据 with open('/Users/samappleton/Documents/Python/Project/api_response_2023-01-31-13:22.json','r') as f: data = json.loads(f.read()) # 第一步:展开casualties,保留所有顶级字段和vehicles列表 df_casualties = pd.json_normalize( data, record_path=['casualties'], meta=['id', 'lat', 'lon', 'location', 'date', 'severity', 'borough', 'vehicles'], record_prefix='casualties.' ) # 第二步:展开vehicles列表,关联到已展开的伤亡数据 df_final = pd.json_normalize( df_casualties.to_dict('records'), record_path=['vehicles'], meta=[col for col in df_casualties.columns if col != 'vehicles'], record_prefix='vehicles.' ) print(df_final)
内容的提问来源于stack exchange,提问作者Samuel Appleton
相关产品推荐
相关产品推荐

