def get_player_shooting_splits(self): for season in self.seasons: player_list = nba_py_player.PlayerList(season=season).info() if isinstance(player_list, pandas.DataFrame): for index, row in player_list.iterrows(): if self.db.player_shooting_splits.count( { "SEASON_ID": season_to_season_id(season), "PLAYER_ID": str(row.PERSON_ID) }) > 0: print( "shooting splits of {} {} already exists, skipping" .format(season, row.DISPLAY_FIRST_LAST)) continue print("retrieving player shooting splits for {} {}".format( season, row.DISPLAY_FIRST_LAST)) shooting_splits = nba_py_player.PlayerShootingSplits( player_id=row.PERSON_ID, season=season).shot_5ft() if isinstance(shooting_splits, pandas.DataFrame): shooting_splits = shooting_splits.to_dict("records") if shooting_splits: for shooting_range in shooting_splits: shooting_range['PLAYER_ID'] = str(row.PERSON_ID) shooting_range['SEASON_ID'] = season_to_season_id( season) shooting_range[ 'PLAYER_NAME'] = row.DISPLAY_FIRST_LAST self.db.player_shooting_splits.insert_many( shooting_splits) else: print("shooting splits of {} {} not found".format( season, row.DISPLAY_FIRST_LAST))
def generate_ast_shot_df(player_id_list, year): lst_of_dicts = [] for id in player_id_list: print id #get the shotchart for player ast_shots = player.PlayerShootingSplits(id, season=year).assisted_shots() if not ast_shots.empty: ast_shots_made = ast_shots.FGM[ast_shots.GROUP_VALUE == 'Assisted'].sum() lst_of_dicts.append({ 'player_id': str(id), 'ast_shot_made': ast_shots_made }) else: lst_of_dicts.append({'player_id': str(id), 'ast_shot_made': 0}) ast_shot_df = pd.DataFrame(lst_of_dicts) ast_shot_df.set_index('player_id', inplace=True, drop=True) return ast_shot_df
def get_player_stats(): my_player = player.PlayerShootingSplits(player_id) stats = my_player.shot_5ft() ## LONG RANGE, MID RANGE, CLOSE RANGE AND FREE THROW SHOOTING ## global field_goals, field_goal_pcts field_goals = stats["FGM"] field_goal_pcts = stats["FG_PCT"] get_2pt_impact(field_goals, field_goal_pcts) get_3pt_impact_and_free_throw() ## DUNKS ## shot_types = my_player.shot_types_summary() shots_made = shot_types["FGM"] dunks = shots_made[2] ## HEIGHT ## height_info = get_player_info("HEIGHT") height = get_inches_calc(height_info) ## ATHLETICISM ## get_athletic_impact(height, dunks) ## SHOTS ASSISTED BY AND TO ## assisted_stats = my_player.assisted_shots() two_shots_made = assisted_stats["FGM"] three_shots_made = assisted_stats["FG3M"] solo_points = get_unassisted_impact(two_shots_made, three_shots_made) points_created = get_passing_stats() get_playmaking_impact(points_created, solo_points) #return get_vertical_leap(1) #return stats ## DEFENSE ## get_defense_impact() #return two_pt_stats + three_pt_and_free_stats global total total = long_range + inside + defense + athletic + playmaking
import nba_py import json import sys import webbrowser import os from nba_py import team as team from nba_py import player as p from nba_py import constants as constants firstName = sys.argv[1] lastName = sys.argv[2] print(firstName + " " + lastName + " " + "Stats") pID = (p.get_player(firstName, lastName)) shootingSplits = p.PlayerShootingSplits(pID).shot_areas() playerInfo = p.PlayerSummary(pID).info() headlineStats = p.PlayerSummary(pID).headline_stats() playerPhotoLink = "http://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/latest/260x190/" + str( pID) + ".png" linkJSON = {} print(json.dumps(headlineStats, indent=4)) print(type(playerInfo)) playerInfo[0]["link"] = playerPhotoLink twoMade = 0 twoAttempted = 0 threeMade = 0 threeAttempted = 0
## General Splits if str(case) == "generalsplits": for name in my_own_namelist.keys(): player_id = my_own_namelist[name] print(name, player_id) season = '2018-19' stats = player.PlayerGeneralSplits(player_id=player_id, season=season).json #print(json.dumps(stats,indent=4,sort_keys=True)) # So for now I don't care about the parameters in the dictionary. I just save them down first. target_dir = str(season) + '\\generalsplits\\' + str( player_id) + '_' + str(name) with open(target_dir, 'w') as f: json.dump(stats, f) elif str(case) == "shootingsplits": for name in my_own_namelist.keys(): player_id = my_own_namelist[name] print(name, player_id) season = '2018-19' stats = player.PlayerShootingSplits(player_id=player_id, season=season).json # print(stats) # print(json.dumps(stats,indent=4,sort_keys=True)) # So for now I don't care about the parameters in the dictionary. I just save them down first. target_dir = str(season) + '\\shootingsplits\\' + str( player_id) + '_' + str(name) with open(target_dir, 'w') as f: json.dump(stats, f) # query_data("shootingsplits")
def get_player_stat(player_id): """ Takes player NBA ID and returns a data frame containing player performance data such as shooting, blocking, rebound etc... """ # Extracting shooting and blocking columns player_shot_block_raw = player.PlayerShootingSplits(player_id, season='2018-19').shot_areas() if player_shot_block_raw.shape[0] == 0: raise NoDataError("No data for {}".format(player_id)) player_shot_and_block_by_area = player_shot_block_raw.T player_shot_and_block_by_area.columns = player_shot_and_block_by_area.loc['GROUP_VALUE'] player_shot_and_block_by_area = player_shot_and_block_by_area.loc[[ 'FGA', 'BLKA'], "Restricted Area":"Above the Break 3"] player_shot_by_area = player_shot_and_block_by_area.loc[["FGA"], :] player_block_by_area = player_shot_and_block_by_area.loc[["BLKA"], :] # Use a dict to map old col name to new col name, using dict is required # because the API sometimes returns inconsistent column order and number # of cols shot_col_map = {"Restricted Area": 'shot_res', "In The Paint (Non-RA)": 'shot_in_paint', "Mid-Range": 'shot_mid_range', 'Left Corner 3': 'shot_lcorner_3', 'Right Corner 3': 'shot_rcorner_3', 'Above the Break 3': 'shot_above_3'} block_col_map = {"Restricted Area": 'block_res', "In The Paint (Non-RA)": 'block_in_paint', "Mid-Range": 'block_mid_range', 'Left Corner 3': 'block_lcorner_3', 'Right Corner 3': 'block_rcorner_3', 'Above the Break 3': 'block_above_3'} # Applying the column name map player_shot_by_area = player_shot_by_area.rename(columns=shot_col_map) player_block_by_area = player_block_by_area.rename(columns=block_col_map) # Total attempted shots and blocks total_shots = player_shot_by_area.loc['FGA', :].sum() total_blocks = player_block_by_area.loc['BLKA', :].sum() # Normalize all stats by total shots to get relative frequencies for each # player player_shot_by_area /= total_shots + 1e-5 player_block_by_area /= total_blocks + 1e-5 # Record total attempted shots and blocks player_shot_by_area['fga'] = total_shots player_block_by_area['blka'] = total_blocks # PlayerYearOverYearSplits is the end point we will be calling # to get player stats aside from shooting and blocking # Take the most recent 2 years, and then add them rebound_assist = player.PlayerYearOverYearSplits( player_id, per_mode="Per48").by_year().iloc[:2, :] cols_of_interest = ['OREB', 'DREB', 'AST', 'STL', "MIN"] rebound_assist = rebound_assist[cols_of_interest] rebound_assist.columns = [c.lower() for c in rebound_assist.columns] rebound_assist_summed = pd.DataFrame(rebound_assist.sum()).T # Finally, concatnate the dataframes together player_stat = pd.concat([player_shot_by_area.reset_index(drop=True), player_block_by_area.reset_index(drop=True), rebound_assist_summed.reset_index(drop=True)], axis=1) player_stat = player_stat.rename({0: player_id}) return player_stat