在Pandas中访问嵌套JSON数据作为数据帧

2024-10-01 17:21:15 发布

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

我有以下数据

{ "results": [
    {
        "company": "XYZ",
        "createdAt": "2014-03-27T23:21:48.758Z",
        "email": "abc@gmail.com",
        "firstName": "abc",
        "lastName": "xyz",
        "linkedinAccount": "",
        "location": "",
        "profilePicture": {
            "__type": "File",
            "name": "ab0e-profilePicture",
            "url": "url.url.com"
        },
        "registrationGate": "normal",
        "telephone": "",
        "title": "AA",
        "updatedAt": "2014-03-27T23:24:20.220Z",
        "username": "abc@gmail.com",
        "zipcode": "00000"
    } 
    ] 
    }

我使用以下代码导入json数据

^{pr2}$

这个指纹

results
0  {u'linkedinAccount': u'', u'username': u'abc...
1  {u'linkedinAccount': u'zxcflcnv', u'username...

[2 rows x 1 columns]

当我试图使用

print df['linkedinAccount']

我得到以下错误

KeyError: u'no item named linkedinAccount'

如何基于列名访问数据帧中的数据?在


Tags: 数据comurlemailusernamefirstnameresultscompany
1条回答
网友
1楼 · 发布于 2024-10-01 17:21:15

不确定您的多个观察结果是如何组织在json中的。但是很明显,导致问题的是"profilePicture"字段有一个嵌套结构。因此,每个观察结果都表示为一个嵌套字典。您需要将每个观察值转换为dataframe,并将其转换为最终的dataframe,如本解决方案中所示。在

In [3]:
print df
                                             results
0  {u'linkedinAccount': u'', u'username': u'abc@g...
1  {u'linkedinAccount': u'', u'username': u'abc@g...

[2 rows x 1 columns]
In [4]: 
print pd.concat([pd.DataFrame.from_dict(item, orient='index').T for item in df.results])


  linkedinAccount       username registrationGate firstName title lastName  \
0                  abc@gmail.com           normal       abc    AA      xyz   
0                  abc@gmail.com           normal       abc    AA      xyz   

  company telephone                                     profilePicture  \
0     XYZ            {u'url': u'url.url.com', u'__type': u'File', u...   
0     ABC            {u'url': u'url.url.com', u'__type': u'File', u...   

  location                 updatedAt          email                 createdAt  \
0           2014-03-27T23:24:20.220Z  abc@gmail.com  2014-03-27T23:21:48.758Z   
0           2014-03-27T23:24:20.220Z  abc@gmail.com  2014-03-27T23:21:48.758Z   

  zipcode  
0   00000  
0   00000  

[2 rows x 14 columns]

然后您可能需要考虑如何处理profilePicture列。你可以按照@U2EF1在链接中的建议来做。但我可能会把这个列分成三列pfPIC_urlpfPIC_typepfPIC_name

相关问题 更多 >

    热门问题