【问题标题】:Python Flatten Multiply Nested Dictionary JSON with PandasPython Flatten 用 Pandas 将嵌套字典 JSON 相乘
【发布时间】:2017-05-05 10:16:26
【问题描述】:

我正在处理一个 JSON 响应,其格式类似于下面的多嵌套字典:

{u'addresses': [],
 u'application_ids': [20855193],
 u'applications': [{u'answers': [{u'answer': u'Indeed ',
                                  u'question': u'How did you hear?'}],
                    u'applied_at': u'2015-10-29T22:19:04.925Z',
                    u'candidate_id': 9999999,
                    u'credited_to': None,
                    u'current_stage': {u'id': 9999999,
                                       u'name': u'Application Review'},
                    u'id': 9999999,
                    u'jobs': [{u'id': 9999999,u'name': u'ENGINEER'}],
                    u'last_activity_at': u'2015-10-29T22:19:04.767Z',
                    u'prospect': False,
                    u'rejected_at': None,
                    u'rejection_details': None,
                    u'rejection_reason': None,
                    u'source': {u'id': 7, u'public_name': u'Indeed'},
                    u'status': u'active'}],
 u'attachments': [{u'filename': u'Jason_Bourne.pdf',
                   u'type': u'resume',
                   u'url': u'https://resumeURL'}],
 u'company': None,
 u'coordinator': {u'employee_id': None,
                  u'id': 9999999,
                  u'name': u'Batman_Robin'},
 u'email_addresses': [{u'type': u'personal',
                       u'value': u'jasonbourne@gmail.com'}],
 u'first_name': u'Jason',
 u'id': 9999999,
 u'last_activity': u'2015-10-29T22:19:04.767Z',
 u'last_name': u'Bourne',
 u'website_addresses': []}

我正在尝试将 JSON 扁平化为表格,并在 pandas 文档中找到以下示例:

http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.io.json.json_normalize.html

据我了解,“record_path”参数指定了您感兴趣的最低级别记录的路径。“record_path”参数只能是字符串,或字符串列表。但是,要调用上面数据中的“答案”记录,我必须指定字符串 索引,如下所示;

answer = data['applications'][0]['answers']['answer']
question = data['applications'][0]['answers']['question']

如何将上面的记录路径作为参数输入到 json_normalize 函数中?

谢谢!

【问题讨论】:

    标签: python json pandas nested


    【解决方案1】:

    我认为你可以使用record_path嵌套list

    from pandas.io.json import json_normalize    
    df = json_normalize(d, ['applications', ['answers']])
    print (df)
        answer           question
    0  Indeed   How did you hear?
    

    【讨论】:

    • 现在我正在尝试为“current_stage”下的“名称”做同样的事情。当我输入df = json_normalize(d, ['applications', ['current_stage','name']]) 时,我会在自己的行中收到“Application Review”的每个字母?
    • 你可以使用df = json_normalize(d['applications'][0]['current_stage']),我尝试了很多方法,不幸的是没有成功。主要问题是{u'id': 9999999, u'name': u'Application Review'} 中缺少[],例如[{u'id': 9999999, u'name': u'Application Review'}]
    猜你喜欢
    • 2021-08-31
    • 2018-05-31
    • 2018-08-01
    • 2021-03-20
    • 2021-09-25
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多