【问题标题】:Split nested json into correct rows using Pandas使用 Pandas 将嵌套的 json 拆分为正确的行
【发布时间】:2022-01-18 16:25:45
【问题描述】:

我从 API 接收到以下 json 文件:

{'get': '夹具/统计数据', “参数”:{“夹具”:“65”}, “错误”:[], “结果”:2, “分页”:{“当前”:1,“总”:1}, '响应':[{'团队':{'id':33, “名称”:“曼彻斯特联队”} 'statistics': [{'type': '射门次数', 'value': 6}, {'type': '射门次数', 'value': 1}, {'type': '总投篮次数', 'value': 8}, {'type': 'Blocked Shots', 'value': 1}]}, {'团队':{'id':46, “名称”:“莱斯特”} 'statistics': [{'type': '射门次数', 'value': 4}, {'type': '射门次数', 'value': 3}, {'type': 'Total Shots', 'value': 13}, {'type': 'Blocked Shots', 'value': 6}]}]}

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

当我跑步时:

results_df = pd.json_normalize(results_json, record_path=["response"])

我明白了:

但是,当我跑步时

results_data = pd.json_normalize(results_json, record_path = ["response", "statistics"])

我明白了:

|   | 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 的统计部分中的数据放入每个响应的正确行中?

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

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

    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
    

    【讨论】:

    • 谢谢你。是否可以在与 team.id 相同的行上获取所有统计信息,这样只会返回 2 行数据,每个团队 1 行。
    • @Clauric 不建议这样做~ :-),如果你喜欢,可以查看 pivot stackoverflow.com/questions/47152691/…,Q&A10
    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2021-08-26
    • 2022-08-19
    • 2020-07-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多