【问题标题】:Accessing nested JSON data as dataframes in Pandas在 Pandas 中将嵌套的 JSON 数据作为数据框访问
【发布时间】:2014-06-06 03:43:33
【问题描述】:

我有以下数据

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

import json
import pandas as pd

from pandas import DataFrame
json_data = pd.read_json('data.json')

print json_data[:2]

这会打印出来

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'

如何根据列名访问数据框中的数据?

【问题讨论】:

标签: python json pandas


【解决方案1】:

不确定json 中的多个观察结果是如何组织的。但很明显,导致问题的原因是您有一个 "profilePicture" 字段的嵌套结构。因此,每个观察都表示为嵌套字典。您需要将每个观察结果转换为dataframeconcat,将它们转换为最终的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

【讨论】:

    猜你喜欢
    • 2017-03-21
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多