【问题标题】:Flattening and constructing new columns into Pandas df from nested json file从嵌套的 json 文件中将新列展平并构建到 Pandas df 中
【发布时间】:2018-11-07 07:34:43
【问题描述】:

我正在使用 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}}

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

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

到目前为止,我的尝试都失败了。我得到的最近的是这个非常幼稚的代码:

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

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

编辑

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

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

【问题讨论】:

  • 请以文本而不是图像的形式提供您想要的输出。

标签: python json pandas


【解决方案1】:

尝试使用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

【讨论】:

  • 我在 pandas 0.23.3 中找不到 json.nested_to_record 吗?你是什​​么版本。
  • '0.19.2' 版本
  • 所以,我们需要寻找替代json_normalize :-)
  • 感谢您的回答。这仅适用于一个条目,但是一个包含多个条目的 json 文件呢?这部分会如何改变?df['author_affiliations']=','.join([i['first_name']+i['last_name'] for i in df['author_affiliations'][0][0]])
猜你喜欢
  • 2022-11-23
  • 2021-02-02
  • 2016-12-01
  • 2021-10-09
  • 2018-09-24
  • 2021-12-16
  • 2021-05-14
  • 2020-09-27
  • 1970-01-01
相关资源
最近更新 更多