python - 使用 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()
数据框如下所示:
有人可以帮我把它变成以下格式:
感谢您在这方面提供任何帮助/建议。谢谢。
解决方案
使用pd.io.json.json_normalize
和meta
+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
推荐阅读
- elixir - 使用 elixir gettext 标记要翻译的字符串列表(在编译时)
- flutter - 如何获取 web-app 的 url 的查询参数?
- asp.net-core - 将 Windows 身份验证与 OpenId (OpenIddict) 一起使用的正确方法是什么?
- javascript - 使用 OpenLayers 的星图
- c++ - 递归二分搜索 - C++
- python - python selenium 3 Edge Web驱动程序中的错误
- c# - 加载页面时打开 CollectionView 的 SelectionChanged 事件
- keras - 为什么模型经常受益于在训练期间降低学习率
- c# - 使用 Protobuf (C#) 存储二维数组
- django - 根据与当前登录的用户相关的用户配置文件,仅在 django admin 上显示那些对象