【问题标题】:How to extract lowest level of a nested JSON into a DataFrame in Python?如何将嵌套 JSON 的最低级别提取到 Python 中的 DataFrame 中?
【发布时间】:2021-10-12 12:41:06
【问题描述】:

我希望只提取 Python 中 JSON 的最低级别对象。例如,API 的前几条记录如下所示:

{
  "season": 2021,
  "charts": {
    "ARI": {
      "TE": [
        {
          "team": "ARI",
          "position": "TE",
          "depth": "1",
          "playerId": "1443",
          "name": "Dan Arnold"
        },
        {
          "team": "ARI",
          "position": "TE",
          "depth": "2",
          "playerId": "599",
          "name": "Maxx Williams"
        }
      ],
      "K": [
        {
          "team": "ARI",
          "position": "K",
          "depth": "1",
          "playerId": "1121",
          "name": "Zane Gonzalez"
        },
        {

我最终希望将所有这些结果放入具有这种结构的 DataFrame 中:

| team | position | depth | playerId | name |
|:---- |:-------- |:----- |:-------- |:---- |

我尝试了以下代码的变体但没有成功:

import requests as rq
import pandas as pd

# Retrieve Depth Charts
json_depthCharts = rq.get(f"https://api.fantasynerds.com/v1/nfl/depth?apikey={API_KEY}").json()

df_depthCharts = pd.json_normalize(json_depthCharts, 'charts', ['charts', 'team'])

print(df_depthCharts)

感谢任何见解!

【问题讨论】:

  • 此外,您提供的链接很有帮助,但您的 API 密钥在其中可见,因此请删除它,如果您有如此大的数据,请在未来将其粘贴到 pastebin 等网站或通过任何其他不利用敏感信息的媒体
  • 先生,您的问题解决了吗?

标签: python json pandas dataframe extract


【解决方案1】:

试试json_normalize()+melt()+explode()+Dataframe():

df=pd.DataFrame(pd.json_normalize(json_depthCharts).melt('season')['value'].explode().tolist())

或

其他方式通过stack()+drop() 组合代替melt(),其余所有方法保持不变:

df=pd.DataFrame(pd.json_normalize(json_depthCharts).drop(columns='season').stack().explode().tolist())

df 的输出:

        team    position    depth   playerId    name
0       ARI     TE          1       1443        Dan Arnold
1       ARI     TE          2       599         Maxx Williams
2       ARI     K           1       1121        Zane Gonzalez
3       ARI     K           2       1454        Brett Maher
4       ARI     LWR         1       338         DeAndre Hopkins
...     ...     ...        ...      ...         ...
932     WAS     LDE         2       179         Ryan Kerrigan
933     WAS     RCB         1       647         Ronald Darby
934     WAS     RB          1       1957        Antonio Gibson
935     WAS     RB          2       1542        Bryce Love
936     WAS     NB          1       1733        Jimmy Moreland

937 rows × 5 columns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 2018-09-01
    • 2016-09-23
    • 2020-11-07
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多