【问题标题】:Creating pandas dataframe from accessing specific keys of nested dictionary通过访问嵌套字典的特定键创建熊猫数据框
【发布时间】:2021-09-17 11:33:18
【问题描述】:

如何将下面的字典转换为如下所示的预期数据帧?

{
    "getArticleAttributesResponse": {
        "attributes": [{
            "articleId": {
                "id": "2345",
                "locale": "en_US"
            },
            "keyValuePairs": [{
                "key": "tags",
                "value": "[{\"displayName\": \"Nice\", \"englishName\": \"Pradeep\", \"refKey\": \"Key2\"}, {\"displayName\": \"Family Sharing\", \"englishName\": \"Sarvendra\", \"refKey\": \"Key1\", \"meta\": {\"customerDisplayable\": [false]}}}]"
            }]
        }]
    }
}

预期的数据框:

    id           displayName              englistname          refKey
    2345            Nice                   Pradeep             Key2
    2345         Family Sharing            Sarvendra           Key1

【问题讨论】:

    标签: python json pandas dataframe dictionary


    【解决方案1】:
    df1 = pd.DataFrame(d['getDDResponse']['attributes']).explode('keyValuePairs')
    df2 = pd.concat([df1[col].apply(pd.Series) for col in df1],1).assign(value = lambda x :x.value.apply(eval)).explode('value')
    df = pd.concat([df2[col].apply(pd.Series) for col in df2],1)
    

    输出:

          0     0     display englishName reference   source
    0  1234  tags  Unarchived  Unarchived    friend  monster
    

    【讨论】:

    • 非常感谢@Nk03 ...对不起,我之前没有发布完整的输入字典和预期的输出数据帧。现在编辑两者。请建议我们该怎么做...请帮助,因为我被阻止了。
    • 我已经编辑了我的原始帖子...字典和预期的数据帧
    猜你喜欢
    • 2019-01-11
    • 2017-01-01
    • 2016-12-17
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 2021-02-15
    • 2021-02-04
    相关资源
    最近更新 更多