【问题标题】:Normalize a deeply nested json in pandas规范化熊猫中深度嵌套的 json
【发布时间】:2020-03-05 11:10:06
【问题描述】:

我正在尝试规范化一个看起来像这样的 json 文件(一个小的 sn-p):

[{'trimestre': 'A2000',
  'cours': [{"sigle":"TECH 20701", "titre":"La cybersécurité et le gestionnaire",'etudiants': [{'matricule': '22000803',
      'nom': 'Boyer,André',
      'note': 'C+',
      'valeur': 2.3},
     {'matricule': '22000829',
      'nom': 'Keighan,Maylis',
      'note': 'A+',
      'valeur': 4.3},
     {'matricule': '22000869',
      'nom': 'Lahaie,Lyes',
      'note': 'B+',
      'valeur': 3.3},
     {'matricule': '22000973',
      'nom': 'Conerardy,Rawaa',
      'note': 'B+',
      'valeur': 3.3},
      ]}]

我正在尝试获得一个如下所示的表格:

                                    **"trimestre"** (columns)
      **"sigle" + "titre"** (index): *valeur*
import pandas as pd
import json
import numpy as np
from pandas.io.json import json_normalize

data = pd.read_json('DataTP2.json')
print(data)

我尝试过像这样使用 normalize 函数

result = json_normalize(data, 'cours',['trimestre'])
print(result) 

但我收到一个错误:TypeError: string indices must be integers

基本上,我希望“sigle”+“titre”(来自“cours”)作为索引,“trimestre”作为列,“valeur”的平均值作为表中的值。

提前致谢!

【问题讨论】:

  • 请不要将输出作为图像发布。在问题中复制过去。从图像中获取数据真的很难。
  • @poojan 抱歉第一次使用堆栈溢出我改变了它。
  • 问题是你有几个'valeur'的1个索引,你想要一个吗?
  • @FlorianBernard 单独使用“sigle”是最好的

标签: python json pandas


【解决方案1】:

你来了:

from collections import defaultdict
import json

with open("data.json", "r") as f:
    data = json.load(f)

test = [{'trimestre': 'A2000',
  'cours': [{"sigle":"TECH 20701", "titre":"La cybersécurité et le gestionnaire",'etudiants': [{'matricule': '22000803',
      'nom': 'Boyer,André',
      'note': 'C+',
      'valeur': 2.3},
     {'matricule': '22000829',
      'nom': 'Keighan,Maylis',
      'note': 'A+',
      'valeur': 4.3},
     {'matricule': '22000869',
      'nom': 'Lahaie,Lyes',
      'note': 'B+',
      'valeur': 3.3},
     {'matricule': '22000973',
      'nom': 'Conerardy,Rawaa',
      'note': 'B+',
      'valeur': 3.3},
      ]}]}]


results = defaultdict(list)

for trimestre in data:
    results["trimestre"].append(trimestre["trimestre"])
    for cours in trimestre["cours"]:
        results["index"].append(f"{cours['sigle']} {cours['titre']}")
        results["valeur"].append(cours["sigle"])

df = pd.DataFrame(results["valeur"], columns=results["trimestre"], index=results["index"])

结果

>>> print(df)
                                                   A2000
TECH 20701 La cybersécurité et le gestionnaire  TECH 20701

【讨论】:

  • 我仍然收到 TypeError: string indices must be integers error when Try your code
  • @Jacky 我已经更新了我的代码,在 pandas 上使用 json 模块。
猜你喜欢
  • 1970-01-01
  • 2020-11-09
  • 2021-12-12
  • 2019-07-19
  • 2019-09-04
  • 2017-12-23
  • 2021-10-04
  • 2021-05-22
  • 2018-05-05
相关资源
最近更新 更多