<jupyter_start><jupyter_text>PSTAT134 Final Project Predicting NBA Player Positions<jupyter_code>import pandas as pd
import numpy as np
import sklearn.decomposition as skld
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
import helper_basketball as h
import imp
imp.reload(h);
def get_nba_data(endpt, params, return_url=False):

    ## endpt: https://github.com/seemethere/nba_py/wiki/stats.nba.com-Endpoint-Documentation
    ## params: dictionary of parameters: i.e., {'LeagueID':'00'}
    
    from pandas import DataFrame 
    from urllib.parse import urlencode
    import json
    
    useragent = "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9\""
    dataurl = "\"" + "http://stats.nba.com/stats/" + endpt + "?" + urlencode(params) + "\""
    
    # for debugging: just return the url
    if return_url:
        return(dataurl)
    
    jsonstr = !wget -q -O - --user-agent={useragent} {dataurl}
    
    data = json.loads(jsonstr[0])
    
    h = data['resultSets'][0]['headers']
    d = data['resultSets'][0]['rowSet']
    
    return(DataFrame(d, columns=h))
def get_nba_dash(params, return_url=False):
    
    from pandas import DataFrame 
    from urllib.parse import urlencode
    import json
    
    useragent = "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9\""
    dataurl = "\"" + "http://stats.nba.com/stats/leaguedashplayerstats" + "?" + urlencode(params) + "\""
    
    # for debugging: just return the url
    if return_url:
        return(dataurl)
    
    jsonstr = !wget -q -O - --user-agent={useragent} {dataurl}
    
    data = json.loads(jsonstr[0])
    
    h = data['resultSets'][0]['headers']
    d = data['resultSets'][0]['rowSet']
    
    return(DataFrame(d, columns=h))
#get all players
params = {'LeagueID':'00', 
          'Season': '2016-17', 
          'IsOnlyCurrentSeason': '0'}
players = get_nba_data('commonallplayers', params)
players = players[players.TO_YEAR == '2017']
players.head()
players.DISPLAY_FIRST_LAST[players.PERSON_ID == 1627826]
#get specific players game stats
params = {'PlayerID':'1627826',
          'Season':'2016-17',
          'SeasonType':'Regular Season'}

gamedata = get_nba_data('playergamelog', params)
gamedata.head()
agg_DF = pd.DataFrame()
#take pieces from three of the endpoints to compile a dataset
#variables: pts, oreb, dreb, reb, ast, blocks, steals, turnovers, position, height, offensive rating, defensive rating,
#assist to TO ratio, assist percent
def get_play_avg(playlist):
    for x in range(0, len(players.PERSON_ID)):
        i = 0
        params = {'PlayerID':players.PERSON_ID.iloc[x],
                  'Season':'2016-17',
                  'SeasonType':'Regular Season'}
        gamedata = get_nba_data('playergamelog', params)
        
        player_params = {'PlayerID':playlist.iloc[x]}
        playerdata = get_nba_data('commonplayerinfo', player_params)
        
        dash_params = {"MeasureType":"Advanced",
                       "PerMode":"PerGame",
                       "PlusMinus":"N",
                       "PaceAdjust":"N",
                       "Rank":"N",
                       "LeagueID":"00",
                       "Season":"2016-17",
                       "SeasonType":"Playoffs",
                       "PORound":'0',
                       "Outcome":'',
                       "Location":'',
                       "Month":'0',
                       "SeasonSegment":'',
                       "DateFrom":'',
                       "DateTo":'',
                       "OpponentTeamID":'0',
                       "VsConference":'',
                       "VsDivision":'',
                       "TeamID":'0',
                       "Conference":'',
                       "Division":'',
                       "GameSegment":'',
                       "Period":'0',
                       "ShotClockRange":'',
                       "LastNGames":'0',
                       "GameScope":'',
                       "PlayerExperience":'',
                       "PlayerPosition":'',
                       "StarterBench":'',
                       "DraftYear":'',
                       "DraftPick":'',
                       "College":'',
                       "Country":'',
                       "Height":'',
                       "Weight":''}
        ratingsdata = get_nba_dash(dash_params)
            
        # agg_DF.loc[x, i + 1] = players.DISPLAY_FIRST_LAST[players.PERSON_ID == players.PERSON_ID.iloc[x]] #needs to be corrected for the datatype    
        
        # agg_DF.loc[x, i + 2] = [playerdata.POSITION]
        # agg_DF.loc[x, i + 3] = [playerdata.HEIGHT]
        # agg_DF.loc[x, i + 4] = ratingsdata.OFF_RATING[ratingsdata.PLAYER_ID == playlist.iloc[x]]
        # agg_DF.loc[x, i + 5] = ratingsdata.DEF_RATING[ratingsdata.PLAYER_ID == playlist.iloc[x]]
        # agg_DF.loc[x, i + 11] = ratingsdata.AST_PCT[ratingsdata.PLAYER_ID == playlist.iloc[x]]
        # agg_DF.loc[x, i + 12] = ratingsdata.AST_RATIO[ratingsdata.PLAYER_ID == playlist.iloc[x]]
        
        agg_DF.loc[x, i] = players.PERSON_ID.iloc[x]
        agg_DF.loc[x, i + 1] = gamedata.PTS.mean()
        agg_DF.loc[x, i + 2] = gamedata.OREB.mean()
        agg_DF.loc[x, i + 3] = gamedata.DREB.mean()
        agg_DF.loc[x, i + 4] = gamedata.REB.mean()
        agg_DF.loc[x, i + 5] = gamedata.AST.mean()
        agg_DF.loc[x, i + 6] = gamedata.STL.mean()
        agg_DF.loc[x, i + 7] = gamedata.BLK.mean()
        agg_DF.loc[x, i + 8] = gamedata.TOV.mean()

    return(agg_DF) #should be the fully compiled dataset that you can perform analysis on
get_play_avg(players.PERSON_ID) 
#run time is kind of long due to for loop, can adjust if you want. look at agg_DF below, it worked before and should look like that
hello = pd.DataFrame(columns = ['play', 'reb'])
hello.loc[0, 0] = players.PERSON_ID.iloc[0]
hello.loc[1, 0] = [players.DISPLAY_FIRST_LAST[players.PERSON_ID == 2544]]

hello
agg_DF
#get specific players common info
player_params = {'PlayerID':'2544'}

playerdata = get_nba_data('commonplayerinfo', player_params)
playerdata.head()
#get specific ratings per player
dash_params = {"MeasureType":"Advanced",
               "PerMode":"PerGame",
               "PlusMinus":"N",
               "PaceAdjust":"N",
               "Rank":"N",
               "LeagueID":"00",
               "Season":"2016-17",
               "SeasonType":"Playoffs",
               "PORound":'0',
               "Outcome":'',
               "Location":'',
               "Month":'0',
               "SeasonSegment":'',
               "DateFrom":'',
               "DateTo":'',
               "OpponentTeamID":'0',
               "VsConference":'',
               "VsDivision":'',
               "TeamID":'0',
               "Conference":'',
               "Division":'',
               "GameSegment":'',
               "Period":'0',
               "ShotClockRange":'',
               "LastNGames":'0',
               "GameScope":'',
               "PlayerExperience":'',
               "PlayerPosition":'',
               "StarterBench":'',
               "DraftYear":'',
               "DraftPick":'',
               "College":'',
               "Country":'',
               "Height":'',
               "Weight":''}
ratingsdata = get_nba_dash(dash_params)
ratingsdata.head()
ratingsdata.OFF_RATING[ratingsdata.PLAYER_ID == players.PERSON_ID.iloc[0]]
list(ratingsdata)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14796188459502382, 'fraction_numerical': 0.019984118581259924, 'mean_word_length': 1.9822415153906867, 'pattern_counts': {'":': 70, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '549101', 'license': 'Apache-2.0', 'n_tokens_mistral': 2601, 'n_tokens_neox': 2406, 'n_words': 464, 'path': 'Final-Project/PSTAT134-Final-Project.ipynb', 'repo_name': 'jstevenr/Spring-2018', 'size': '7556'}