【发布时间】:2022-01-24 19:11:16
【问题描述】:
我有大量 JSON 数据,我想执行一些任务。 所以我为此选择了熊猫。
我有一个这样的嵌套 json:
json_data = [
{
"item": "Item1",
"lowestPrice": {
"price": 11.00,
"currency": "EUR",
},
},
{
"item": "Item2",
"lowestPrice": {
"price": 12.00,
"currency": "EUR",
}
},
{
"item": "Item3",
"lowestPrice": {
"price": 13.00,
"currency": "EUR",
}
}
]
我使用 json_normalize() 来规范嵌套的 json,例如:
df = pd.json_normalize(json_data, max_level=2)
item lowestPrice.price lowestPrice.currency
0 Item1 11.0 EUR
1 Item2 12.0 EUR
2 Item3 13.0 EUR
#do something
现在我需要以嵌套 JSON 或 dict 形式返回数据,例如:
json_data = [
{
"item": "Item1",
"lowestPrice": {
"price": 11.00,
"currency": "EUR",
},
"annotatePrice": 15.00
},
{
"item": "Item2",
"lowestPrice": {
"price": 12.00,
"currency": "EUR",
},
"annotatePrice": 15.00
},
{
"item": "Item3",
"lowestPrice": {
"price": 13.00,
"currency": "EUR",
},
"annotatePrice": 15.00
}
]
【问题讨论】:
-
这能回答你的问题吗? Pandas convert Dataframe to Nested Json。您可以使用
df.columns = df.columns.str.split('.', expand=True)创建多索引 -
@Peter 不,先生。感谢您的宝贵时间
-
如果我的回答对您有帮助,您可以投票/接受吗?如果有什么可以改进的,请告诉我们。
-
你好@KabilanMohanraj,我赞成你的回答,是的,它在某种程度上很有帮助,但我的数据非常嵌套。所以你能帮我更多吗??
-
我认为新数据将超出这个问题的范围。我目前的答案是基于已提供的输入和输出。那么,你能接受我对它的回答解决了这个问题吗?对于新数据,请创建一个新问题?我们可以在那里讨论。
标签: python json pandas dataframe dictionary