获取LeBron投篮数据时返回空DataFrame,求问题排查
问题分析与修复方案
你的代码导致空DataFrame有几个关键问题,逐个解决:
1. season_type_all_star参数格式错误
NBA API的ShotChartDetail中,season_type_all_star只接受单个字符串值,不能传入列表。如果要同时获取常规赛和季后赛数据,需要分别发起请求再合并结果。
2. 未调用数据获取方法
创建ShotChartDetail实例后,必须调用get_data_frames()方法才能提取DataFrame数据,你现在只打印了实例对象,并没有实际获取数据。
3. 变量覆盖问题(非直接原因,但建议修复)
你导入了players和teams模块后,又用同名变量存储它们的返回结果,容易引发混淆,建议重命名变量。
修复后的完整代码
from nba_api.stats.endpoints import shotchartdetail from nba_api.stats.static import players as static_players from nba_api.stats.static import teams as static_teams import pandas as pd # 获取球员和球队列表,避免覆盖模块 player_list = static_players.get_players() team_list = static_teams.get_teams() # 获取LeBron的ID bron = [player for player in player_list if player['full_name'] == 'LeBron James'][0] bron_id = bron['id'] # 获取湖人ID(这里可以不用,但保留逻辑) lakers = [team for team in team_list if team['full_name'] == 'Los Angeles Lakers'][0] lal_id = lakers['id'] # 分别请求常规赛和季后赛数据 shotlog_regular = shotchartdetail.ShotChartDetail( team_id=0, player_id=str(bron_id), # 用获取到的ID更稳妥,也可以直接写'2544' context_measure_simple='FGA', season_type_all_star='Regular Season' ).get_data_frames()[0] shotlog_playoffs = shotchartdetail.ShotChartDetail( team_id=0, player_id=str(bron_id), context_measure_simple='FGA', season_type_all_star='Playoffs' ).get_data_frames()[0] # 合并两个数据集 shotlog_lebron = pd.concat([shotlog_regular, shotlog_playoffs], ignore_index=True) # 查看结果 print(shotlog_lebron.shape) print(shotlog_lebron.head())
关键说明
get_data_frames()返回的是一个列表,第一个元素就是投篮数据的DataFrame,所以取[0]。- 如果只需要某一类赛事(比如仅常规赛),直接对应设置
season_type_all_star为单个字符串即可。
内容的提问来源于stack exchange,提问作者Filip Wojtczak
相关产品推荐
相关产品推荐

