python - 有没有更好的方法将 JSON 转换为 DataFrame?

标签 python json pandas

想要将 JSON 对象转换为 DataFrame。

这是我的 JSON 对象

data = {'situation': {'OpenPlay': {'shots': 282,
   'goals': 33,
   'xG': 36.38206055667251,
   'against': {'shots': 276, 'goals': 29, 'xG': 33.0840025995858}},
  'FromCorner': {'shots': 46,
   'goals': 2,
   'xG': 2.861613758839667,
   'against': {'shots': 46, 'goals': 4, 'xG': 3.420699148438871}},
  'DirectFreekick': {'shots': 19,
   'goals': 1,
   'xG': 1.0674087516963482,
   'against': {'shots': 10, 'goals': 0, 'xG': 0.6329493299126625}},
  'SetPiece': {'shots': 14,
   'goals': 1,
   'xG': 0.6052199145779014,
   'against': {'shots': 21, 'goals': 1, 'xG': 2.118571280501783}},
  'Penalty': {'shots': 6,
   'goals': 6,
   'xG': 4.5670130252838135,
   'against': {'shots': 2, 'goals': 1, 'xG': 1.5222634673118591}}}

想要输出:

enter image description here

我的代码:

df = pd.json_normalize(data['situation']['OpenPlay'])

for i in range(1,4):
    df = df.append(pd.json_normalize(data['situation'][type_of_play[i]]))
    
df = df.reset_index()

有什么有效的方法可以做到这一点吗?

最佳答案

首先,您的数据末尾缺少“}”。 试试这个代码:

obj = [pd.json_normalize(data['situation'][e]) for e in data['situation']]
pd.concat(obj, ignore_index=True)

enter image description here

关于python - 有没有更好的方法将 JSON 转换为 DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67140699/

相关文章:

python - tkinter 的 IntVar() 和 .get()'ing

python - 使用 unstack() reshape pandas 数据框

python - Kivy - 在 ModalView 中按下按钮后更改屏幕

javascript - 在更新我的 Angular View 之前,如何操作从 JSON 响应派生的对象?

python - 根据其他列值标记行

javascript - 如何使用 Flask 将 Canvas url 转换为图像 numpy 数组?

javascript - typescript :无法将值从 json 转换为 [number, number] 元组

json - SwiftyJSON 生成空白字符串值

python - 如何将值映射到位?

python - 根据逗号将一列拆分为几列