[英]nested dictionary to pandas Dataframe within a list
I have a nested Dictionary list which is...我有一个嵌套的字典列表,它是......
order = [
{
'order_id' : 1,
'status' : 'processing',
'line_items': [
{
'product_id': 2,
'product_name' : 'mango'
},
{
'product_id':4,
'product_name': 'orange'
}
],
},
{
'order_id' : 2,
'status' : 'processing',
'line_items': [
{
'product_id': 3,
'product_name' : 'banana'
}
]
},
]
I want to get a Dataframe like this...我想得到一个像这样的 Dataframe ......
order_id status line_items
0 1 processing product_id: 2,
product_name: mango
product_id:4
product_name: orange
1 2 processing product_id': 3
product_name: banana
I have tried like this我试过这样
df_order = pd.DataFrame(order)
and other various ways but could not solve the problem.和其他各种方法,但无法解决问题。
You can use pd.json_normalize
.您可以使用pd.json_normalize
。 I think you should stop there.我认为你应该停在那里。 I've taken the liberty of trying to make it look more like your desired output, but I think that's a terrible way of representing the data compared to what it looked like before .set_index(...).stack()
.我冒昧地试图让它看起来更像你想要的 output,但我认为与.set_index(...).stack()
之前的样子相比,这是一种糟糕的数据表示方式。
df = (pd.json_normalize(order, ['line_items'], ['order_id', 'status'])
.set_index(['order_id', 'status'])
.stack())
df.index.names = ['order_id', 'status', 'line_items']
print(df)
Output. Output。
order_id status line_items
1 processing product_id 2
product_name mango
product_id 4
product_name orange
2 processing product_id 3
product_name banana
dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.