【问题标题】:change json structure of column data frame pandas with nested json使用嵌套 json 更改列数据框 pandas 的 json 结构
【发布时间】:2022-11-12 10:37:25
【问题描述】:

抱歉,我想问一下我想用嵌套的 json 更改 pandas 数据框列的 json 结构

但是在尝试搜索了几个来源后都没有找到解决方案。也许这里有人可以帮忙,请帮忙!

谢谢

对于这样的代码:

import pandas as pd
import json
d = {'id': ['xxx'], 'user': ['asdam']}
df = pd.DataFrame(data=d)
result = df.to_json(orient="records")
parsed = json.loads(result)
json.dumps(parsed, indent=4)

对于 json,我希望它看起来像这样: {'id':'xxx','user':{'display_name':'asdam'}}

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用 lambda 函数(有点奇怪,但它有效):

    import pandas as pd
    import json
    d = {'id': ['xxx'], 'user': ['asdam']}
    df = pd.DataFrame(data=d)
    df['user']=df['user'].apply(lambda x: {'display_name':x}) # create a dictionary with row value
    result = df.to_json(orient="records")
    parsed = json.loads(result)
    parsed =json.dumps(parsed, indent=4)
    print(parsed)
    '''
    [
        {
            "id": "xxx",
            "user": {
                "display_name": "asdam"
            }
        }
    ]
    '''
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 2022-07-13
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多