如何将cfbd博彩API返回的数据转换为含指定列的Pandas DataFrame
数据转换代码
你可以直接在原有代码的try语句块,拿到api_response后补充以下逻辑即可完成转换,使用前请确认已安装pandas库,未安装可先执行pip install pandas。
整合后完整可运行代码
import pandas as pd import cfbd from cfbd.rest import ApiException configuration = cfbd.Configuration() configuration.api_key['Authorization'] = 'XXX' # 替换为你自己的API密钥 configuration.api_key_prefix['Authorization'] = 'Bearer' # 初始化API实例 api_instance = cfbd.BettingApi(cfbd.ApiClient(configuration)) try: # 获取博彩数据 api_response = api_instance.get_lines(year=2021, week=7, season_type='regular', conference='SEC') # 转换数据为目标DataFrame data_list = [] for game in api_response: # 此处取第一个盘口数据,如需保留所有博彩商的盘口,可改为遍历game.lines line = game.lines[0] data_list.append({ "away_team": game.away_team, "home_team": game.home_team, "spread": line.spread, "overUnder": line.over_under }) # 生成DataFrame并转换数值类型 df = pd.DataFrame(data_list) df["spread"] = df["spread"].astype(float) df["overUnder"] = df["overUnder"].astype(float) # 输出验证 print(df.head()) except ApiException as e: print("调用BettingApi.get_lines接口出错: %s\n" % e)
输出效果示例
最终生成的df结构如下:
| away_team | home_team | spread | overUnder |
|---|---|---|---|
| Auburn | Arkansas | -3.5 | 53.5 |
| Kentucky | Georgia | -23.5 | 44.5 |
| Florida | LSU | 10.0 | 58.5 |
注:如果单场比赛存在多个博彩商的盘口数据,你只需要把
line = game.lines[0]替换为内层遍历for line in game.lines:即可生成包含所有盘口的DataFrame,也可额外添加provider字段保留博彩商信息。
内容的提问来源于stack exchange,提问作者Pmannn
相关产品推荐
相关产品推荐

