【问题标题】:List of jsons to Pandas dataframePandas 数据框的 json 列表
【发布时间】:2020-11-22 02:05:54
【问题描述】:

我一直在将多个 JSON 文件附加到一个列表中,并将该列表导出为名为“Merged_file.json”的文件。现在我无法将 JSON 对象列表转换为 Pandas 数据框。数据集如下所示:

[
  {
    "ids": {
        "parts": [
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8"
        ]
    },
    "process": true,
    "indexes": [],
    "metadata": {
        "m_13": {
            "description": "This is a test",
            "confidence": {
                "state": "pre-added",
                "who": [
                    "user:George"
                ],
                "prob": 1
            }
        }
    }
  }
]

如何将“元数据”对象及其包含的所有不同值提取到 Pandas 数据框中? 在将结果附加到列表之前,我可以简单地使用 json_normalize 提取列,并拥有这样的工作代码。任何人都可以帮助这个具体的例子,还是我应该附加到列表以外的东西?

编辑: 预期输出:

Index    |Description     |State      |Who 
0         This is a test   pre-added   George
  • 所以我想从不同的嵌套对象中获取值。这只是“元数据”中的第一个。想象一下,再有 12 个这样的结构。

【问题讨论】:

  • 你能显示你尝试过的代码吗?这里还有很多类似的相关问题。那么这个 Q 有什么不同呢?
  • @maverick 你在想什么代码?追加到列表代码还是提取代码?

标签: python json pandas list


【解决方案1】:

使用json_normalize 你可以这样做:

with open('1.json', 'r+') as f:
    data = json.load(f)

df = pd.json_normalize(data, 
                       record_path=['metadata', 'm_13', 'confidence', 'who'],
                       meta=[['metadata', 'm_13', 'description'],
                            ['metadata', 'm_13', 'confidence', 'state'],
                            ['metadata', 'm_13', 'confidence', 'prob']])
print(df)

             0 metadata.m_13.description metadata.m_13.confidence.state metadata.m_13.confidence.prob
0  user:George            This is a test                      pre-added                             1

【讨论】:

  • 非常感谢!你的解决方案做到了:D
猜你喜欢
  • 2018-07-19
  • 1970-01-01
  • 2020-09-02
  • 2021-02-09
  • 2018-02-05
  • 2021-09-27
  • 2018-08-11
  • 2015-12-14
  • 2017-12-03
相关资源
最近更新 更多