想要将 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}}}
想要输出:
我的代码:
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)
关于python - 有没有更好的方法将 JSON 转换为 DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67140699/