首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Pandas将嵌套的json拆分为正确的行

使用Pandas将嵌套的json拆分为正确的行
EN

Stack Overflow用户
提问于 2022-01-18 16:25:45
回答 1查看 119关注 0票数 0

从API接收到以下json文件:

{“获取”:“夹具/统计数据”,“参数”:{“夹具”:'65'},‘错误’:[],‘结果’:2,‘分页’:{‘当前’:1,‘总计’:1},‘响应’:[ {'id':33,‘名称’:‘曼彻斯特联队’}‘统计数据’:{‘类型’:‘射门’,‘值’:6},{“类型”:“关闭目标”、“值”:1}、{“类型”:“总射击”、“值”:8}、{“类型”:“阻止射击”、“值”:1}、{“团队”:{“id”:46、“名称”:“莱斯特”}统计信息:{“类型”:“目标上的射击”、“值”:4}、{“类型”:“射击离开目标”,'value':3},{'type':‘总计’,'value':13},{'type':‘阻止’,'value':6}

我正在尝试将统计部分中的数据与团队信息放在相同的行中。

当我跑步时:

代码语言:javascript
复制
results_df = pd.json_normalize(results_json, record_path=["response"])

我得到:

但是,当我跑的时候

代码语言:javascript
复制
results_data = pd.json_normalize(results_json, record_path = ["response", "statistics"])

我得到:

代码语言:javascript
复制
|   | type           | value |
|---|----------------|-------|
| 0 | Shots on Goal  | 6     |
| 1 | Shots off Goal | 1     |
| 2 | Total Shots    | 8     |
| 3 | Blocked Shots  | 1     |
| 4 | Shots on Goal  | 4     |
| 5 | Shots off Goal | 3     |
| 6 | Total Shots    | 13    |
| 7 | Blocked Shots  | 6     |

在上面,行0-3对应于team.id = 33,而第4-7行对应于team.id - 46。

是否有任何方法将来自json的统计部分的数据输入到每个响应的正确行中?

EN

回答 1

Stack Overflow用户

发布于 2022-01-18 16:40:39

我们可以用explode修改当前的输出

代码语言:javascript
复制
s = pd.json_normalize(result_json, record_path=["response"]).explode('statistics').reset_index(drop=True)
s = s.join(pd.DataFrame(s.pop('statistics').tolist()))
s
Out[112]: 
   team.id          team.name            type  value
0       33  Manchester United   Shots on Goal      6
1       33  Manchester United  Shots off Goal      1
2       33  Manchester United     Total Shots      8
3       33  Manchester United   Blocked Shots      1
4       46          Leicester   Shots on Goal      4
5       46          Leicester  Shots off Goal      3
6       46          Leicester     Total Shots     13
7       46          Leicester   Blocked Shots      6
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70759003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档