Python中如何从博彩API响应为DataFrame添加盘口赔率列
提取NCAAF博彩API中让分盘(Spreads)的Price值到DataFrame
首先明确这类博彩API的典型嵌套结构(以常见格式为例),单场比赛数据大概长这样:
{ "home_team": "Ohio State", "away_team": "Michigan", "commence_time": "2024-11-30T17:30:00Z", "markets": [ { "key": "spreads", "outcomes": [ {"type": "home", "price": -110, "point": -7.5}, {"type": "away", "price": -110, "point": +7.5} ] }, # 其他市场如大小分等 ] }
方法1:通过球队类型(home/away)提取价格
写一个自定义函数遍历嵌套结构,提取指定球队类型的让分盘价格:
def extract_spread_price(game, team_type): # 遍历所有市场,定位让分盘市场 for market in game.get("markets", []): if market.get("key") == "spreads": # 遍历该市场的结果项,匹配球队类型 for outcome in market.get("outcomes", []): if outcome.get("type") == team_type: return outcome.get("price") # 找不到对应数据时返回None return None
假设你已经有API返回的原始数据列表api_raw_data,以及已创建的DataFramegame_df,直接用列表推导式添加列:
# 添加主队让分盘价格列 game_df["home_spread_price"] = [extract_spread_price(game, "home") for game in api_raw_data] # 添加客队让分盘价格列 game_df["away_spread_price"] = [extract_spread_price(game, "away") for game in api_raw_data]
方法2:通过球队名称匹配提取(如果API返回的outcome用球队名而非类型)
如果API的让分盘结果里没有type字段,而是直接用球队名称(比如name字段对应球队名),修改函数为:
def extract_spread_price_by_name(game, team_name): for market in game.get("markets", []): if market.get("key") == "spreads": for outcome in market.get("outcomes", []): if outcome.get("name") == team_name: return outcome.get("price") return None
然后结合DataFrame里的球队名称列进行匹配:
# 遍历DataFrame索引,匹配对应球队的让分盘价格 game_df["home_spread_price"] = [ extract_spread_price_by_name(api_raw_data[i], game_df.loc[i, "home_team"]) for i in game_df.index ] game_df["away_spread_price"] = [ extract_spread_price_by_name(api_raw_data[i], game_df.loc[i, "away_team"]) for i in game_df.index ]
注意事项
- 如果你的API结构和示例有差异(比如让分盘的
key不是spreads,或者价格字段叫odds而非price),只需要修改函数里的字段名即可。 - 也可以用
pd.Series.apply替代列表推导式,逻辑完全一致。
内容的提问来源于stack exchange,提问作者tcmax55
相关产品推荐
相关产品推荐

