首页 > 解决方案 > 使用 Pandas 处理订单 json 数据

问题描述

我有订单的 JSON 数据,如下所示:

[
    {
        "id": 640197558336,
        "line_items": [
            {
                "id": 1501742661696,
                "variant_id": 19490901426240,
                "title": "\"Acrylic Bag\"",
                "quantity": 1
            },
            {
                "id": 1501742661695,
                "variant_id": 19490901426245,
                "title": "\"Trash Can\"",
                "quantity": 2
            }
        ]
    },
    {
        "id": 640197558337,
        "line_items": [
            {
                "id": 1501742661699,
                "variant_id": 19490901426249,
                "title": "\"Sports headphones\"",
                "quantity": 5
            },
            {
                "id": 1501742661695,
                "variant_id": 19490901426245,
                "title": "\"Trash Can\"",
                "quantity": 6
            }
        ]
    }
]

我曾经pandas 阅读过 json 并将其视为数据框,请参见下文:

import pandas as pd

desired_width = 920
file_name = "trimmedorders"
file_ext = ".json"
pd.set_option('display.width', desired_width)

df = pd.read_json(file_name+file_ext,orient='columns')
df.head()

数据框如下所示:

在此处输入图像描述

有人可以帮我把它变成以下格式:

在此处输入图像描述

感谢您在这方面提供任何帮助/建议。谢谢。

标签: pythonpandasdataframe

解决方案


使用pd.io.json.json_normalizemeta+record_path关键字:

from pandas.io.json import json_normalize

df = pd.concat([
    json_normalize(row, record_path=["line_items"], record_prefix="line_item_", meta="id")
        for row in data
])

>> print(df)

    line_item_id  line_item_quantity      line_item_title  \
0  1501742661696                   1        "Acrylic Bag"   
1  1501742661695                   2          "Trash Can"   
0  1501742661699                   5  "Sports headphones"   
1  1501742661695                   6          "Trash Can"   

   line_item_variant_id            id  
0        19490901426240  640197558336  
1        19490901426245  640197558336  
0        19490901426249  640197558337  
1        19490901426245  640197558337  

请注意,这比@Rakesh 的解决方案更昂贵,因为每次都json_normalize返回 a 。DataFrame


推荐阅读