pandas json_normalize 具有非常嵌套的 json

2023-11-27

我一直在努力normalize一个非常嵌套的 json 文件,我稍后将进行分析。我正在努力解决的是如何进一步深入正常化。

我经历了pandas.io.json.json_normalize文档,因为它完全按照我想要的方式执行。

我已经能够将其中的一部分标准化,现在了解字典是如何工作的,但我仍然不在那里。

使用下面的代码我只能获得第一级。

import json
import pandas as pd
from pandas.io.json import json_normalize

with open('authors_sample.json') as f:
    d = json.load(f)

raw = json_normalize(d['hits']['hits'])

authors = json_normalize(data=d['hits']['hits'], 
                         record_path='_source', 
                         meta=['_id',
                               ['_source', 'journal'],
                               ['_source', 'title'], 
                               ['_source', 'normalized_venue_name']
                              ])

我试图用下面的代码“挖掘”“作者”字典,但是record_path = ['_source', 'authors']把我扔了TypeError: string indices must be integers。据我所理解json_normalize逻辑应该很好,但我仍然不太明白如何深入研究 jsondict vs list.

我什至经历过这个简单的example.

authors = json_normalize(data=d['hits']['hits'], 
                         record_path=['_source', 'authors'], 
                         meta=['_id',
                               ['_source', 'journal'],
                               ['_source', 'title'], 
                               ['_source', 'normalized_venue_name']
                              ])

下面是 json 文件的一部分(5 条记录)。

{u'_shards': {u'failed': 0, u'successful': 5, u'total': 5},
 u'hits': {u'hits': [{u'_id': u'7CB3F2AD',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': None,
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'Physical Review Letters',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'phys rev lett',
     u'pages': None,
     u'parent_keywords': [u'Chromatography',
      u'Quantum mechanics',
      u'Particle physics',
      u'Quantum field theory',
      u'Analytical chemistry',
      u'Quantum chromodynamics',
      u'Physics',
      u'Mass spectrometry',
      u'Chemistry'],
     u'pub_date': u'1987-03-02 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'mass spectra', u'elementary particles', u'bound states'],
     u'title': u'Evidence for a new meson: A quasinuclear NN-bar bound state',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'Physical Review Letters',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7AF8EBC3',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'affiliations': [u'Punjabi University'],
       u'author_id': u'780E3459',
       u'author_name': u'munish puri'},
      {u'affiliations': [u'Punjabi University'],
       u'author_id': u'48D92C79',
       u'author_name': u'rajesh dhaliwal'},
      {u'affiliations': [u'Punjabi University'],
       u'author_id': u'7D9BD37C',
       u'author_name': u'r s singh'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'Journal of Industrial Microbiology & Biotechnology',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'j ind microbiol biotechnol',
     u'pages': None,
     u'parent_keywords': [u'Nuclear medicine',
      u'Psychology',
      u'Hydrology',
      u'Chromatography',
      u'X-ray crystallography',
      u'Nuclear fusion',
      u'Medicine',
      u'Fluid dynamics',
      u'Thermodynamics',
      u'Physics',
      u'Gas chromatography',
      u'Radiobiology',
      u'Engineering',
      u'Organic chemistry',
      u'High-performance liquid chromatography',
      u'Chemistry',
      u'Organic synthesis',
      u'Psychotherapist'],
     u'pub_date': u'2008-04-04 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'flow rate',
      u'operant conditioning',
      u'packed bed reactor',
      u'immobilized enzyme',
      u'specific activity'],
     u'title': u'Development of a stable continuous flow immobilized enzyme reactor for the hydrolysis of inulin',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'Journal of Industrial Microbiology & Biotechnology',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7521A721',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'7FF872BC',
       u'author_name': u'barbara eileen ryan'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Social science',
      u'Politics',
      u'Sociology',
      u'Law'],
     u'pub_date': u'1992-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'social movements'],
     u'title': u"Feminism and the women's movement : dynamics of change in social movement ideology, and activism",
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7DAEB9A4',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'0299B8E9',
       u'author_name': u'fraser j harbutt'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Superconductivity',
      u'Nuclear fusion',
      u'Geology',
      u'Chemistry',
      u'Metallurgy'],
     u'pub_date': u'1988-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'iron'],
     u'title': u'The iron curtain : Churchill, America, and the origins of the Cold War',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7B3236C5',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'7DAB7B72',
       u'author_name': u'richard m freeland'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Political Science', u'Economics'],
     u'pub_date': u'1985-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'foreign policy'],
     u'title': u'The Truman Doctrine and the origins of McCarthyism : foreign policy, domestic politics, and internal security, 1946-1948',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'}],
  u'max_score': 1.0,
  u'total': 36429433},
 u'timed_out': False,
 u'took': 170}
 

在 pandas 示例(如下)中,括号是什么意思?是否有一个逻辑可以遵循以深入了解[]。[...]

result = json_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']])

中的每个字符串或字符串列表['state', 'shortname', ['info', 'governor']]value 是要包含的元素的路径,除了选定的行之外。第二个论点json_normalize()争论 (record_path, 设置'counties'在文档示例中)告诉函数如何从输入数据结构中选择组成输出行的元素,以及meta路径添加了将包含在每行中的更多元数据。如果愿意的话,可以将它们视为数据库中的表连接。

输入为the 美国各州文档示例列表中有两个字典,并且这两个字典都有一个counties引用另一个字典列表的键:

>>> data = [{'state': 'Florida',
...          'shortname': 'FL',
...         'info': {'governor': 'Rick Scott'},
...         'counties': [{'name': 'Dade', 'population': 12345},
...                      {'name': 'Broward', 'population': 40000},
...                      {'name': 'Palm Beach', 'population': 60000}]},
...         {'state': 'Ohio',
...          'shortname': 'OH',
...          'info': {'governor': 'John Kasich'},
...          'counties': [{'name': 'Summit', 'population': 1234},
...                       {'name': 'Cuyahoga', 'population': 1337}]}]
>>> pprint(data[0]['counties'])
[{'name': 'Dade', 'population': 12345},
 {'name': 'Broward', 'population': 40000},
 {'name': 'Palm Beach', 'population': 60000}]
>>> pprint(data[1]['counties'])
[{'name': 'Summit', 'population': 1234},
 {'name': 'Cuyahoga', 'population': 1337}]

它们之间有 5 行数据用于输出:

>>> json_normalize(data, 'counties')
         name  population
0        Dade       12345
1     Broward       40000
2  Palm Beach       60000
3      Summit        1234
4    Cuyahoga        1337

The meta然后参数命名了一些存在的元素next对那些counties列表,然后将它们分别合并。从第一个开始的值data[0]字典为那些meta元素是('Florida', 'FL', 'Rick Scott'),分别为data[1]值为('Ohio', 'OH', 'John Kasich'),所以您会看到附加到的这些值counties来自同一顶级字典的行,分别重复 3 次和 2 次:

>>> data[0]['state'], data[0]['shortname'], data[0]['info']['governor']
('Florida', 'FL', 'Rick Scott')
>>> data[1]['state'], data[1]['shortname'], data[1]['info']['governor']
('Ohio', 'OH', 'John Kasich')
>>> json_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']])
         name  population    state shortname info.governor
0        Dade       12345  Florida        FL    Rick Scott
1     Broward       40000  Florida        FL    Rick Scott
2  Palm Beach       60000  Florida        FL    Rick Scott
3      Summit        1234     Ohio        OH   John Kasich
4    Cuyahoga        1337     Ohio        OH   John Kasich

因此,如果您传递一个列表meta参数,则列表中的每个元素都是一个单独的路径,并且每个单独的路径都标识要添加到输出中的行的数据。

In your例如 JSON,只有几个嵌套列表需要使用第一个参数进行提升,例如'counties'在例子中做了。该数据结构中唯一的例子是嵌套'authors'钥匙;你必须提取每个['_source', 'authors']路径,之后您可以添加父对象中的其他键来扩充这些行。

第二meta然后论证_id键来自最外层的对象,然后是嵌套的['_source', 'title'] and ['_source', 'journal']嵌套路径。

The record_path论证采用authors列表作为起点,这些看起来像:

>>> d['hits']['hits'][0]['_source']['authors']   # this value is None, and is skipped
>>> d['hits']['hits'][1]['_source']['authors']
[{'affiliations': ['Punjabi University'],
  'author_id': '780E3459',
  'author_name': 'munish puri'},
 {'affiliations': ['Punjabi University'],
  'author_id': '48D92C79',
  'author_name': 'rajesh dhaliwal'},
 {'affiliations': ['Punjabi University'],
  'author_id': '7D9BD37C',
  'author_name': 'r s singh'}]
>>> d['hits']['hits'][2]['_source']['authors']
[{'author_id': '7FF872BC',
  'author_name': 'barbara eileen ryan'}]
>>> # etc.

所以给你以下几行:

>>> json_normalize(d['hits']['hits'], ['_source', 'authors'])
           affiliations author_id          author_name
0  [Punjabi University]  780E3459          munish puri
1  [Punjabi University]  48D92C79      rajesh dhaliwal
2  [Punjabi University]  7D9BD37C            r s singh
3                   NaN  7FF872BC  barbara eileen ryan
4                   NaN  0299B8E9     fraser j harbutt
5                   NaN  7DAB7B72   richard m freeland

然后我们可以使用第三个meta添加更多列的参数,例如_id, _source.title and _source.journal, using ['_id', ['_source', 'journal'], ['_source', 'title']]:

>>> json_normalize(
...     data['hits']['hits'],
...     ['_source', 'authors'],
...     ['_id', ['_source', 'journal'], ['_source', 'title']]
... )
           affiliations author_id          author_name       _id   \
0  [Punjabi University]  780E3459          munish puri  7AF8EBC3  
1  [Punjabi University]  48D92C79      rajesh dhaliwal  7AF8EBC3
2  [Punjabi University]  7D9BD37C            r s singh  7AF8EBC3
3                   NaN  7FF872BC  barbara eileen ryan  7521A721
4                   NaN  0299B8E9     fraser j harbutt  7DAEB9A4
5                   NaN  7DAB7B72   richard m freeland  7B3236C5

                                     _source.journal
0  Journal of Industrial Microbiology & Biotechno...
1  Journal of Industrial Microbiology & Biotechno...
2  Journal of Industrial Microbiology & Biotechno...
3                     The American Historical Review
4                     The American Historical Review
5                     The American Historical Review

                                       _source.title  \
0  Development of a stable continuous flow immobi...
1  Development of a stable continuous flow immobi...
2  Development of a stable continuous flow immobi...
3  Feminism and the women's movement : dynamics o...
4  The iron curtain : Churchill, America, and the...
5  The Truman Doctrine and the origins of McCarth...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pandas json_normalize 具有非常嵌套的 json 的相关文章

随机推荐

  • GetxControllers 是否会自动关闭 obs 流?

    我正在使用以下包https pub dev packages get 我需要在 GetxController 的 onClose 中关闭我的 obs 吗 我在文档中找不到任何关于此的信息 看看我的记忆 它们似乎正在被自动销毁 到目前为止我对
  • 如何在 Django Formwizard 1.4 中动态重复步骤?

    我试图根据步骤中的复选框有条件地重复 Django Formwizard Django 1 4 中的步骤 该表单创建一个对象 并有一个复选框 希望 允许他们重复该步骤并使用相同的表单创建同一模型的另一个对象 我看到了这个答案 Django
  • 如何在不破坏原数组的情况下对数组进行排序?

    我有原始数组 public static void main String arg int array 1 5 6 8 4 2 for int i 0 i lt array length i System out print List 1
  • 打开时默认状态为“未知”

    我经常看到人们使用OPEN未明确指定的语句STATUS 在 Fortran 90 和 2008 标准中 这是关于STATUS 如果指定 UNKNOWN 则状态取决于处理器 如果省略此说明符 则默认值为 UNKNOWN 我将其解释为 如果ST
  • 使用 XStream 从 XML 文件生成 Java 类

    我有很多 xml 文件 我想使用 XStream 来管理它们 是否可以使用 XStream 生成与我的 xml 文件相对应的 java 类 XStream是一个用于将 Java 对象序列化为 XML 以及从 XML 反序列化的软件 XStr
  • 提高性能的最佳方法(并包括某种故障转移)

    我们有一个应用程序正在运行 其中 IIS 和 SQL 在同一台计算机上 它是一个windows2003standard 服务器 在VM 上运行4gigs RAM 现在用户数量正在不断增长 还有一些巨大的统计数据 它们可以由用户运行 但对其他
  • C# 2.0 中的 HashSet 替换

    I using List
  • 无法从中央传输工件 org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 (http://repo1.maven.org/maven2)

    我在 SpringSource Tool Suite 中创建了一个新的 Maven 项目 我在我的新 Maven 项目中收到此错误 转移失败 org apache maven plugins maven surefire plugin po
  • 无需下载即可获取文件大小

    如何从 URL 获取文件大小 在 Flutter 中 我可以通过使用以下方式获得它 http Response response await http get url print response contentLength 但这会下载整个
  • Python:PyQt QTreeview 示例 - 选择

    我正在使用 Python 2 7 和 Qt 设计器 并且我是 MVC 新手 我在 Qt 中完成了一个视图 为我提供了目录树列表 以及用于运行事物的控制器 我的问题是 给定 Qtree 视图 选择目录后如何获取目录 代码快照如下 我怀疑它是
  • 扩展 Django 的通用视图

    我正在用 Django 编写我的第一个应用程序 但我遇到了一个问题create object通用视图 在我的urls py 我有 r new CreateView as view 问题是 当用户提交 新 表单时 我需要操作将保存到数据库的数
  • 使用 Java 的文件资源管理器 - 如何进行?

    我准备使用 Java 创建一个文件浏览器 目的是尽可能模仿默认浏览器的行为 无论底层操作系统是什么 我没有用 Java 做过任何 GUI 编程 我已经查找了 Swing SWT 和 JFace 并且我将通过本教程开始我的项目 http ww
  • window.navigator.userAgent 真的会被弃用吗?

    I just 在 MDN 上阅读关于window navigator userAgent 已弃用 此功能已从 Web 标准中删除 尽管某些浏览器可能仍然支持它 但它正在开发中 被丢弃 不要在旧项目或新项目中使用它 页面或网络应用程序 使用它
  • 使用 gdb/gdbserver 远程调试共享库

    我的问题是关于使用 gdb gdbserver 远程调试嵌入式 Arm 处理器上的应用程序 我可以调试应用程序本身 但应用程序动态链接到实现内部通信协议的共享库 我希望能够在共享库函数中设置断点 因此尝试找出一些设备发现问题 我已确保该库使
  • 将 RxJS Observable 收集到数组

    我想使用 RxJS 将异步事件世界与同步世界 桥接 具体来说 我想创建一个函数 它返回在某个时间间隔内收集的事件数组 我可以创建 Observable 来执行我想要的操作 var source Rx Observable interval
  • 无法识别“pip”[重复]

    这个问题在这里已经有答案了 我尝试安装PySide但我从 powershell 收到错误如下 pip The term pip is not recognized as the name of a cmdlet function scrip
  • 检测可移动介质的弹出/插入

    我正在开发一个项目 需要能够检测何时插入或移除 CD 或 USB 驱动器 我发现一些源代码本应执行此操作 但是 当我插入或弹出 CD 时 似乎没有任何反应 有人可以验证来源是否正确 并指出我在这里可能做错了什么吗 public class
  • 有人可以解释一下这个 C++ typedef 吗?

    我已经有一段时间没有使用 C 了 刚刚开始使用它 虽然大部分内容都有道理 但有些地方我发现有点混淆 例如 有人可以解释一下这一行的作用吗 typedef bool OptionManager OptionHandler const ABSt
  • Android 加速度计精度(惯性导航)

    我正在考虑为 Android 手机实现惯性导航系统 但我意识到考虑到加速度计的精度和读数的持续波动 这很难 首先 我将手机放在平坦的表面上 并在 X 和 Y 方向上采样了 1000 个加速度计读数 与桌子平行 因此这些方向上没有重力作用 然
  • pandas json_normalize 具有非常嵌套的 json

    我一直在努力normalize一个非常嵌套的 json 文件 我稍后将进行分析 我正在努力解决的是如何进一步深入正常化 我经历了pandas io json json normalize文档 因为它完全按照我想要的方式执行 我已经能够将其中