通过访问嵌套字典的特定键创建dataframe

2024-09-28 05:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

{
    "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

Tags: 数据id字典familyattributesnicekey2key1
1条回答
网友
1楼 · 发布于 2024-09-28 05:20:51
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

相关问题 更多 >

    热门问题