首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫:嵌套json/dict to json_normalize DataFrame和json_normalize DataFrame to nested /dict

熊猫:嵌套json/dict to json_normalize DataFrame和json_normalize DataFrame to nested /dict
EN

Stack Overflow用户
提问于 2022-01-24 10:00:44
回答 1查看 264关注 0票数 1

我有大量的JSON数据,我想执行一些任务。所以我选择熊猫来做这个。

我有这样一个嵌套的json:

代码语言:javascript
复制
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,如:

代码语言:javascript
复制
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返回:

代码语言:javascript
复制
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
    }
]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-24 10:40:02

首先,我将列annotatePrice添加到dataframe。然后为lowestPrice构造内部字典,然后构造外部字典。我从这个stack answer中获得了我的解决方案。

下面是添加annotatePrice列后的数据。

转换代码:

代码语言:javascript
复制
df = pd.json_normalize(json_data, max_level=2)
df['annotatePrice'] = 15

json_data = (df.groupby(['item', 'annotatePrice'])
       .apply(lambda x: x[['lowestPrice.price', 'lowestPrice.currency']].rename(columns={"lowestPrice.price":'price', "lowestPrice.currency":'currency'}).to_dict('records')[0])
       .reset_index()
       .rename(columns={0:'lowestPrice'})
       .to_dict(orient='records'))

json_data

输出:

代码语言:javascript
复制
[
  {
        'annotatePrice': 15,
        'item': 'Item1',
        'lowestPrice': {
            'currency': 'EUR',
            'price': 11.0
        }
    },
    {
        'annotatePrice': 15,
        'item': 'Item2',
        'lowestPrice': {
            'currency': 'EUR',
            'price': 12.0
        }
    },
    {
        'annotatePrice': 15,
        'item': 'Item3',
        'lowestPrice': {
            'currency': 'EUR',
            'price': 13.0
        }
    }
]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70832010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档