python - 从嵌套的 json 文件将新列展平并构建到 Pandas df 中

标签 python json pandas

我正在使用 Python 3.7.0,我目前面临一个找不到解决方案的问题。考虑以下来自 API 的单个数据条目:

data = {'publications': [{'title': 'The effect of land‐use changes on the hydrological behaviour of Histic Andosols in south Ecuador',
   'author_affiliations': [[{'first_name': 'W.',
      'last_name': 'Buytaert',
      'researcher_id': 'ur.01136506420.02',
      'affiliations': [{'id': 'grid.442123.2',
        'name': 'University of Cuenca',
        'org_types': ['Education'],
        'city': 'Cuenca',
        'city_id': 3658666,
        'country': 'Ecuador',
        'country_code': 'EC',
        'state': None,
        'state_code': None},
       {'id': 'grid.5596.f',
        'name': 'KU Leuven',
        'org_types': ['Education'],
        'city': 'Leuven',
        'city_id': 2792482,
        'country': 'Belgium',
        'country_code': 'BE',
        'state': None,
        'state_code': None}]},
     {'first_name': 'G.',
      'last_name': 'Wyseure',
      'researcher_id': 'ur.012246446667.91',
      'affiliations': [{'id': 'grid.5596.f',
        'name': 'KU Leuven',
        'org_types': ['Education'],
        'city': 'Leuven',
        'city_id': 2792482,
        'country': 'Belgium',
        'country_code': 'BE',
        'state': None,
        'state_code': None}]},
     {'first_name': 'B.',
      'last_name': 'De Bièvre',
      'researcher_id': 'ur.013305075217.11',
      'affiliations': [{'id': 'grid.442123.2',
        'name': 'University of Cuenca',
        'org_types': ['Education'],
        'city': 'Cuenca',
        'city_id': 3658666,
        'country': 'Ecuador',
        'country_code': 'EC',
        'state': None,
        'state_code': None}]},
     {'first_name': 'J.',
      'last_name': 'Deckers',
      'researcher_id': 'ur.0761456127.40',
      'affiliations': [{'id': 'grid.5596.f',
        'name': 'KU Leuven',
        'org_types': ['Education'],
        'city': 'Leuven',
        'city_id': 2792482,
        'country': 'Belgium',
        'country_code': 'BE',
        'state': None,
        'state_code': None}]}]],
   'FOR': [{'id': '2539',
     'name': '0406 Physical Geography and Environmental Geoscience'}],
   'issn': ['0885-6087', '1099-1085'],
   'journal': {'id': 'jour.1043737', 'title': 'Hydrological Processes'},
   'type': 'article',
   'research_org_country_names': ['Belgium', 'Ecuador'],
   'doi': '10.1002/hyp.5867',
   'year': 2005,
   'times_cited': 72}],
 '_stats': {'total_count': 957, 'limit': 1, 'offset': 0}}

我的目标是构建一个数据框,其中嵌套字典最终组合在一起(用逗号分隔),在其他情况下,组合更复杂。为了给出一个想法,我正在寻找的是具有以下结构的东西:

desired data frame

对于“author_affiliations”列,这是最棘手的一列。考虑到我在上面输入的条目,对于第一作者来说,这应该是 'W. Buytaert(厄瓜多尔昆卡大学;比利时鲁汶大学)'等...

到目前为止,我的尝试都惨遭失败。我得到的最近的代码是这个非常天真的代码:

from pandas.io.json import json_normalize
data = data['publications']   
df = json_normalize(data)

我知道我有很多类似的问题。但是,我还没有发现类似的东西(或者至少我没有那么容易注意到)。感谢您的意见和帮助。

编辑

按照评论中的建议,我将所需的输出作为文本:

FOR              |  author_affiliations                                                |doi              | issn                | journal.id   |    journal.title       | countries       | times_cited | title          | type    | year
0406 Physical... | W. Buytaert (University of Cuenca, Ecuador;KU Leuven, Belgium), ... | 10.1002/hyp.5867| 0885-6087,1099-1085 | jour.1043737 | Hydrological Processes | Belgium,Ecuador |      72     | The effect ... | article | 2005

最佳答案

尝试使用 nested_to_record,然后转换为 pandas 数据框,然后手动更改列:

from pandas.io import json
data = data['publications']   
df = json.nested_to_record(data)
df=pd.DataFrame(df)
df['FOR']=df['FOR'].tolist()[0][0]['name']
df['author_affiliations']=','.join([i[0]['first_name']+i[0]['last_name']+' ('+i[0]['affiliations'][0]['name']+', '+i[0]['affiliations'][0]['country']+';'+i[0]['affiliations'][1]['name']+', '+i[0]['affiliations'][1]['country'] for i in df['author_affiliations'][0]])
df['issn']=','.join(df['issn'][0])
df['research_org_country_names']=','.join(df['research_org_country_names'][0])

现在:

print(df)

是(显示为图像,jupyter notebook 结果,因为对于我的闲置来说太大了):


注意:json.nested_to_record 产生错误,改为执行 json.json_normalize

关于python - 从嵌套的 json 文件将新列展平并构建到 Pandas df 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53165334/

相关文章:

python - 使用 Pandas 获取 DataFrame 中的每小时数据

python - 将值是不同长度列表的字典转换为数据框

python - 禁用除在被调用函数中完成的打印之外的所有打印

python - 从 json 中的脚本输出中抓取

python - 将 C++ 类序列化为文件,然后在 Python 中进行基于事件的反序列​​化?

json - jq - 将复杂的 JSON 解析为字符串

javascript - 保存 JSON 响应

python - 将元素添加到 pandas 中的空数据框中

python - MatrixSymbol 中的 Sympy 下划线以 pretty-print 方式更改外观

python - 类型错误 : first argument must be string or compiled pattern