You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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_teamhome_teamspreadoverUnder
AuburnArkansas-3.553.5
KentuckyGeorgia-23.544.5
FloridaLSU10.058.5

注:如果单场比赛存在多个博彩商的盘口数据,你只需要把line = game.lines[0]替换为内层遍历for line in game.lines:即可生成包含所有盘口的DataFrame,也可额外添加provider字段保留博彩商信息。

内容的提问来源于stack exchange,提问作者Pmannn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:24:00