API响应作为数据帧的列表

2024-09-25 00:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难弄清楚如何将API响应中的值解析为列表到数据帧

“games”API响应是一个列表,但它看起来非常类似于JSON。在其他例子中,我能够创建一个dict。此列表有多个级别,创建dict并不容易。我正在边学边用,希望能得到任何帮助

参考:https://github.com/CFBD/cfbd-python/blob/master/docs/GamesApi.md#get_team_game_stats

Python

from __future__ import print_function
import time
import cfbd
from cfbd.rest import ApiException
from pprint import pprint
import pandas as pd
from pandas.io.json import json_normalize
import json
import numpy as np
from datetime import datetime

# Configure API key authorization: ApiKeyAuth
configuration = cfbd.Configuration()
configuration.api_key['Authorization'] = 'xxxxxx'
configuration.api_key_prefix['Authorization'] = 'Bearer'
api_instance = cfbd.BettingApi(cfbd.ApiClient(configuration))

now = datetime.now()
start_year = 2020
end_year = now.year

for x,y in zip(range(start_year, end_year), range(1, 18)):
    year = x # int | Year filter
    week = y # int | Week filter (optional)

    try:
        api_instance = cfbd.GamesApi(cfbd.ApiClient(configuration))
        games = api_instance.get_team_game_stats(year=year, week=week)
        #game_stats_df = pd.DataFrame.from_records([dict(id = g.id, conference = g.conference, homeAway = g.homeAway) for g in games])

    except ApiException as e:
        print("Exception when calling BettingApi->get_calendar: %s\n" % e)

API响应

 {'id': 401238035,
 'teams': [{'conference': None,
            'homeAway': 'away',
            'points': 35,
            'school': 'Central Arkansas',
            'stats': [{'category': 'tacklesForLoss', 'stat': '8'},
                      {'category': 'defensiveTDs', 'stat': '1'},
                      {'category': 'tackles', 'stat': '61'},
                      {'category': 'sacks', 'stat': '0'},
                      {'category': 'qbHurries', 'stat': '1'},
                      {'category': 'passesDeflected', 'stat': '0'},
                      {'category': 'fumblesRecovered', 'stat': '2'},
                      {'category': 'rushingTDs', 'stat': '1'},
                      {'category': 'puntReturnYards', 'stat': '2'},
                      {'category': 'puntReturnTDs', 'stat': '0'},
                      {'category': 'puntReturns', 'stat': '2'},
                      {'category': 'passingTDs', 'stat': '3'},
                      {'category': 'kickReturnYards', 'stat': '116'},
                      {'category': 'kickReturnTDs', 'stat': '0'},
                      {'category': 'kickReturns', 'stat': '4'},
                      {'category': 'kickingPoints', 'stat': '5'},
                      {'category': 'interceptionYards', 'stat': '34'},
                      {'category': 'interceptionTDs', 'stat': '0'},
                      {'category': 'passesIntercepted', 'stat': '1'},
                      {'category': 'interceptions', 'stat': '1'},
                      {'category': 'fumblesLost', 'stat': '2'},
                      {'category': 'turnovers', 'stat': '3'},
                      {'category': 'totalPenaltiesYards', 'stat': '0-0'},
                      {'category': 'yardsPerRushAttempt', 'stat': '4.8'},
                      {'category': 'rushingAttempts', 'stat': '21'},
                      {'category': 'rushingYards', 'stat': '100'},
                      {'category': 'yardsPerPass', 'stat': '4.2'},
                      {'category': 'completionAttempts', 'stat': '25-46'},
                      {'category': 'netPassingYards', 'stat': '193'},
                      {'category': 'totalYards', 'stat': '293'},
                      {'category': 'fourthDownEff', 'stat': '0-0'},
                      {'category': 'thirdDownEff', 'stat': '0-0'},
                      {'category': 'firstDowns', 'stat': '0'}]},
           {'conference': 'Conference USA',
            'homeAway': 'home',
            'points': 45,
            'school': 'UAB',
            'stats': [{'category': 'tacklesForLoss', 'stat': '5'},
                      {'category': 'defensiveTDs', 'stat': '0'},
                      {'category': 'tackles', 'stat': '39'},
                      {'category': 'sacks', 'stat': '2'},
                      {'category': 'qbHurries', 'stat': '5'},
                      {'category': 'passesDeflected', 'stat': '5'},
                      {'category': 'fumblesRecovered', 'stat': '2'},
                      {'category': 'rushingTDs', 'stat': '3'},
                      {'category': 'puntReturnYards', 'stat': '-2'},
                      {'category': 'puntReturnTDs', 'stat': '0'},
                      {'category': 'puntReturns', 'stat': '1'},
                      {'category': 'passingTDs', 'stat': '3'},
                      {'category': 'kickReturnYards', 'stat': '49'},
                      {'category': 'kickReturnTDs', 'stat': '0'},
                      {'category': 'kickReturns', 'stat': '3'},
                      {'category': 'kickingPoints', 'stat': '9'},
                      {'category': 'interceptionYards', 'stat': '19'},
                      {'category': 'interceptionTDs', 'stat': '0'},
                      {'category': 'passesIntercepted', 'stat': '1'},
                      {'category': 'interceptions', 'stat': '1'},
                      {'category': 'fumblesLost', 'stat': '2'},
                      {'category': 'turnovers', 'stat': '3'},
                      {'category': 'totalPenaltiesYards', 'stat': '0-0'},
                      {'category': 'yardsPerRushAttempt', 'stat': '4.8'},
                      {'category': 'rushingAttempts', 'stat': '49'},
                      {'category': 'rushingYards', 'stat': '233'},
                      {'category': 'yardsPerPass', 'stat': '6.6'},
                      {'category': 'completionAttempts', 'stat': '24-34'},
                      {'category': 'netPassingYards', 'stat': '226'},
                      {'category': 'totalYards', 'stat': '459'},
                      {'category': 'fourthDownEff', 'stat': '0-0'},
                      {'category': 'thirdDownEff', 'stat': '0-0'},
                      {'category': 'firstDowns', 'stat': '0'}]}]}]

Tags: fromimportapi列表statsyearconfigurationdict
1条回答
网友
1楼 · 发布于 2024-09-25 00:24:37

我是想帮忙。解决方案可能是像这样使用json_normalize导入:from pandas import json_normalize

我能够用https://jsonformatter.curiousconcept.com稍微清理一下API响应。也就是说它是RFC 8259数据(我对此一无所知,但可能有帮助):

data = {
   "id":401238035,
   "teams":[
      {
         "conference":"None",
         "homeAway":"away",
         "points":35,
         "school":"Central Arkansas",
         "stats":[
            {
               "category":"tacklesForLoss",
               "stat":"8"
            },
            {
               "category":"defensiveTDs",
               "stat":"1"
            },
            {
               "category":"tackles",
               "stat":"61"
            },
            {
               "category":"sacks",
               "stat":"0"
            },
            {
               "category":"qbHurries",
               "stat":"1"
            },
            {
               "category":"passesDeflected",
               "stat":"0"
            },
            {
               "category":"fumblesRecovered",
               "stat":"2"
            },
            {
               "category":"rushingTDs",
               "stat":"1"
            },
            {
               "category":"puntReturnYards",
               "stat":"2"
            },
            {
               "category":"puntReturnTDs",
               "stat":"0"
            },
            {
               "category":"puntReturns",
               "stat":"2"
            },
            {
               "category":"passingTDs",
               "stat":"3"
            },
            {
               "category":"kickReturnYards",
               "stat":"116"
            },
            {
               "category":"kickReturnTDs",
               "stat":"0"
            },
            {
               "category":"kickReturns",
               "stat":"4"
            },
            {
               "category":"kickingPoints",
               "stat":"5"
            },
            {
               "category":"interceptionYards",
               "stat":"34"
            },
            {
               "category":"interceptionTDs",
               "stat":"0"
            },
            {
               "category":"passesIntercepted",
               "stat":"1"
            },
            {
               "category":"interceptions",
               "stat":"1"
            },
            {
               "category":"fumblesLost",
               "stat":"2"
            },
            {
               "category":"turnovers",
               "stat":"3"
            },
            {
               "category":"totalPenaltiesYards",
               "stat":"0-0"
            },
            {
               "category":"yardsPerRushAttempt",
               "stat":"4.8"
            },
            {
               "category":"rushingAttempts",
               "stat":"21"
            },
            {
               "category":"rushingYards",
               "stat":"100"
            },
            {
               "category":"yardsPerPass",
               "stat":"4.2"
            },
            {
               "category":"completionAttempts",
               "stat":"25-46"
            },
            {
               "category":"netPassingYards",
               "stat":"193"
            },
            {
               "category":"totalYards",
               "stat":"293"
            },
            {
               "category":"fourthDownEff",
               "stat":"0-0"
            },
            {
               "category":"thirdDownEff",
               "stat":"0-0"
            },
            {
               "category":"firstDowns",
               "stat":"0"
            }
         ]
      },
      {
         "conference":"Conference USA",
         "homeAway":"home",
         "points":45,
         "school":"UAB",
         "stats":[
            {
               "category":"tacklesForLoss",
               "stat":"5"
            },
            {
               "category":"defensiveTDs",
               "stat":"0"
            },
            {
               "category":"tackles",
               "stat":"39"
            },
            {
               "category":"sacks",
               "stat":"2"
            },
            {
               "category":"qbHurries",
               "stat":"5"
            },
            {
               "category":"passesDeflected",
               "stat":"5"
            },
            {
               "category":"fumblesRecovered",
               "stat":"2"
            },
            {
               "category":"rushingTDs",
               "stat":"3"
            },
            {
               "category":"puntReturnYards",
               "stat":"-2"
            },
            {
               "category":"puntReturnTDs",
               "stat":"0"
            },
            {
               "category":"puntReturns",
               "stat":"1"
            },
            {
               "category":"passingTDs",
               "stat":"3"
            },
            {
               "category":"kickReturnYards",
               "stat":"49"
            },
            {
               "category":"kickReturnTDs",
               "stat":"0"
            },
            {
               "category":"kickReturns",
               "stat":"3"
            },
            {
               "category":"kickingPoints",
               "stat":"9"
            },
            {
               "category":"interceptionYards",
               "stat":"19"
            },
            {
               "category":"interceptionTDs",
               "stat":"0"
            },
            {
               "category":"passesIntercepted",
               "stat":"1"
            },
            {
               "category":"interceptions",
               "stat":"1"
            },
            {
               "category":"fumblesLost",
               "stat":"2"
            },
            {
               "category":"turnovers",
               "stat":"3"
            },
            {
               "category":"totalPenaltiesYards",
               "stat":"0-0"
            },
            {
               "category":"yardsPerRushAttempt",
               "stat":"4.8"
            },
            {
               "category":"rushingAttempts",
               "stat":"49"
            },
            {
               "category":"rushingYards",
               "stat":"233"
            },
            {
               "category":"yardsPerPass",
               "stat":"6.6"
            },
            {
               "category":"completionAttempts",
               "stat":"24-34"
            },
            {
               "category":"netPassingYards",
               "stat":"226"
            },
            {
               "category":"totalYards",
               "stat":"459"
            },
            {
               "category":"fourthDownEff",
               "stat":"0-0"
            },
            {
               "category":"thirdDownEff",
               "stat":"0-0"
            },
            {
               "category":"firstDowns",
               "stat":"0"
            }
         ]
      }
   ]
}

也许这有帮助:

import json
import pandas as pd
from pandas import json_normalize

new_data = data['teams'][0]

dict_data = dict(new_data)

result = json_normalize(new_data, ['stats'], record_prefix='_', errors='ignore')

result 

输出:

^{tb1}$

相关问题 更多 >