使用pd.json_normalize展开嵌套JSON时如何保留上层orderId字段
解决方法
你只需要调整meta参数的写法,通过嵌套列表指定要提取的上层字段的完整路径即可,不需要额外依赖第三方工具,完全使用pd.json_normalize原生能力实现:
import pandas as pd j =[ { "orders": [ { "orderId": 0, "items": [ { "item_1": "x", "item_price": 5.99 }, { "item_1": "y", "item_price": 15.99 } ] } ] } ] df = pd.json_normalize( j, record_path = ['orders', 'items'], meta = [['orders', 'orderId']] # 嵌套列表指定需要提取的上层字段路径 ) print(df)
输出结果:
item_1 item_price orders.orderId 0 x 5.99 0 1 y 15.99 0
拓展用法:自定义列名
如果需要自定义关联字段的列名,可以将meta参数的元素替换为元组,第三个值为自定义列名:
df = pd.json_normalize( j, record_path = ['orders', 'items'], meta = [('orders', 'orderId', 'order_id')] )
输出结果:
item_1 item_price order_id 0 x 5.99 0 1 y 15.99 0
内容的提问来源于stack exchange,提问作者Umar.H
相关产品推荐
相关产品推荐

