【问题标题】:Using JSON with pandas, problem with nested info (python)将 JSON 与 pandas 一起使用,嵌套信息问题(python)
【发布时间】:2020-02-29 22:41:59
【问题描述】:

我正在尝试使用JSON 文件来创建带有pandas 的表。

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


releves = pd.read_json('DataTP2.json')
releves

我的文件结构如下:

[
  {
    "trimestre":"H2012",
    "cours":[
      {
        "sigle":"TECH 20701",
        "titre":"La cybersécurité et le gestionnaire",
        "etudiants":[
          {
            "matricule":"22003545",
            "nom":"Lahaie,Olivier",
            "note":"A+",
            "valeur": 4.3
          },

等等。

使用 read_json 时,表格不会显示嵌套的信息,而是将每个缩进较少的项目显示为一行:

|Cours|Trimestre|

我想要的输出是:

|etudiant|nom|matricule|note|valeur|sigle|titre|trimestre|

我曾尝试使用normalize_json,但出现以下错误:

AttributeError: 'str' object has no attribute 'itervalues'

我尝试在使用 normalize 之前转换为字典,但弹出另一个错误。 谁能帮我摆脱这个障碍?

谢谢

【问题讨论】:

    标签: python json pandas nested normalize


    【解决方案1】:

    嘿,这应该会使你的 json 变平

    json_normalize(arr, record_path=['cours', 'etudiants'], 
               meta=['trimestre', ['cours', 'sigle'], ['cours', 'titre']], 
               record_prefix='etudiant_')
    

    【讨论】:

    • 这在使用 pd.read_json 时不起作用,但在使用“打开方式”时起作用,知道为什么吗?谢谢
    • pd.read_json 不会规范化您的 json。 json_normalize 需要“打开方式”,因为它需要一个 python obj 作为输入
    猜你喜欢
    • 2012-12-23
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2017-06-10
    • 2018-05-29
    • 2015-10-19
    • 2015-08-02
    相关资源
    最近更新 更多