如何使用nba_api正确获取指定多赛季的球员比赛日志?
解决nba_api获取多赛季球员比赛数据的问题
playergamelog.PlayerGameLog的season参数不支持传入列表,只能接受单个赛季字符串,这就是你传列表后结果异常的核心原因。要获取2021赛季至今的球员比赛数据,你可以通过循环遍历目标赛季,逐个请求数据后合并成完整数据集。
实现步骤
- 明确nba_api的赛季格式:赛季参数用赛季起始年份表示,比如2020-21赛季对应
'2020',2023-24赛季对应'2023'。2021赛季至今的目标赛季列表应为['2020', '2021', '2022', '2023'](覆盖2020-21到2023-24赛季)。 - 循环遍历每个赛季,调用
PlayerGameLog接口获取单赛季数据,将每个赛季的DataFrame存入列表,最后合并所有数据。
完整代码示例
from nba_api.stats.static import players from nba_api.stats.endpoints import playergamelog import pandas as pd # 获取卢卡·东契奇的球员ID player_dict = players.get_players() luka = [player for player in player_dict if player['full_name'] == 'Luka Doncic'][0] luka_id = luka['id'] # 定义2021赛季至今的赛季列表(对应2020-21到2023-24赛季) target_seasons = ['2020', '2021', '2022', '2023'] # 初始化空列表存储各赛季数据 all_gamelogs = [] # 循环请求每个赛季的比赛日志 for season in target_seasons: gamelog = playergamelog.PlayerGameLog(player_id=luka_id, season=season) # 将接口返回数据转为DataFrame并添加到列表 gamelog_df = gamelog.get_data_frames()[0] all_gamelogs.append(gamelog_df) # 合并所有赛季的数据 combined_gamelog = pd.concat(all_gamelogs, ignore_index=True) # 验证合并结果 print(f"总比赛场次:{combined_gamelog.shape[0]}") print(combined_gamelog[['SEASON_ID', 'GAME_DATE', 'PTS', 'REB', 'AST']].head())
额外提示
- 若只需从2021-22赛季开始获取数据,直接调整
target_seasons为['2021', '2022', '2023']即可。 - 批量请求时建议添加短暂延迟(比如
time.sleep(1),需先导入time模块),避免触发API请求频率限制。
内容的提问来源于stack exchange,提问作者Claire Gehlhausen
相关产品推荐
相关产品推荐

