0

I was using pandas to convert the NBA API JSON format to csv, and am getting a traceback error. Now I will note I ran into another traceback error a few days ago, but this one is different.

This error is troubling me in particularly because the same code worked earlier in the program. Here is the error in the console: Traceback (most recent call last):

  File "nbagamestats.py", line 48, in <module>
    dfLoop.columns = headersLoop
  File "C:\Users\*\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\generic.py", line 5149, in __setattr__
    return object.__setattr__(self, name, value)
  File "pandas\_libs\properties.pyx", line 66, in pandas._libs.properties.AxisProperty.__set__
  File "C:\Users\*\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\generic.py", line 564, in _set_axis
    self._mgr.set_axis(axis, labels)
  File "C:\Users\*\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\internals\managers.py", line 226, in set_axis
    raise ValueError(
ValueError: Length mismatch: Expected axis has 0 elements, new values have 24 elements

Also, here is all the code I've written:

from nba_api.stats.endpoints import boxscoretraditionalv2
from nba_api.stats.endpoints import shotchartdetail
import pandas as pd
import json
from openpyxl import Workbook

print('Game ID?')
gamenum = input()

### PART ONE - Player List###
response = boxscoretraditionalv2.BoxScoreTraditionalV2(
    end_period = 0,
    game_id= gamenum

)

content = json.loads(response.get_json())

# transform contents into dataframe
results = content['resultSets'][0]
headers = results['headers']
rows = results['rowSet']
df = pd.DataFrame(rows)
df.columns = headers

playerList = df['PLAYER_ID'].tolist()
print(playerList)


###PART TWO - Download Player Shotchart Data###
for i in playerList :
    filename = str(i) +'.xlsx'
    responseLoop = shotchartdetail.ShotChartDetail(
        team_id= 0,
        #last_n_games = numGames,
        game_id_nullable = gamenum,
        player_id= i
    )

    contentLoop = json.loads(responseLoop.get_json())

    # transform contents into dataframe
    resultsLoop = contentLoop['resultSets'][0]
    headersLoop = resultsLoop['headers']
    rowsLoop = resultsLoop['rowSet']
    dfLoop = pd.DataFrame(rowsLoop)
    dfLoop.columns = headersLoop

    # write to excel file
    dfLoop.to_excel(filename, index=False)
    print(i + ' has been written')

Hopefully, yall can help, thanks.

chitown88
  • 27,527
  • 4
  • 30
  • 59
Lazed
  • 9
  • 2

1 Answers1

0

Ok, so ya, to get the playoffs, you need to add that parameter in there (or I should say change it from the default which is "Regular Season". The shotchart is only returning Made shots, not missed shots (again because of the default). So another paramter you'd need to change if you want all shot attempts is also listed below:

from nba_api.stats.endpoints import boxscoretraditionalv2
from nba_api.stats.endpoints import shotchartdetail
import pandas as pd
import json
from openpyxl import Workbook

#print('Game ID?')
#gamenum = input()
gamenum = '0041900404'

### PART ONE - Player List###
response = boxscoretraditionalv2.BoxScoreTraditionalV2(
    end_period = 0,
    game_id= gamenum

)

content = json.loads(response.get_json())

# transform contents into dataframe
results = content['resultSets'][0]
headers = results['headers']
rows = results['rowSet']
df = pd.DataFrame(rows,columns=headers)

playerList = df['PLAYER_ID'].tolist()
print(playerList)



###PART TWO - Download Player Shotchart Data###
for i in playerList :
    filename = str(i) +'.xlsx'
    responseLoop = shotchartdetail.ShotChartDetail(
        team_id= 0,
        season_type_all_star = 'Playoffs', #<-- change to 'Playoffs' - default is 'Regular Season' I believe
        context_measure_simple = 'FGA', #<-- Default is 'PTS' and will only return made shots
        game_id_nullable = gamenum,
        player_id= i
    )

    contentLoop = json.loads(responseLoop.get_json())

    # transform contents into dataframe
    resultsLoop = contentLoop['resultSets'][0]
    headersLoop = resultsLoop['headers']
    rowsLoop = resultsLoop['rowSet']
    dfLoop = pd.DataFrame(rowsLoop,columns=headersLoop)

    # write to excel file
    dfLoop.to_excel(filename, index=False)
    print(str(i) + ' has been written')

Output example:

print(dfLoop.to_string())
            GRID_TYPE     GAME_ID  GAME_EVENT_ID  PLAYER_ID   PLAYER_NAME     TEAM_ID           TEAM_NAME  PERIOD  MINUTES_REMAINING  SECONDS_REMAINING   EVENT_TYPE                     ACTION_TYPE       SHOT_TYPE    SHOT_ZONE_BASIC         SHOT_ZONE_AREA  SHOT_ZONE_RANGE  SHOT_DISTANCE  LOC_X  LOC_Y  SHOT_ATTEMPTED_FLAG  SHOT_MADE_FLAG GAME_DATE  HTM  VTM
0   Shot Chart Detail  0041900404             61       2544  LeBron James  1610612747  Los Angeles Lakers       1                  5                 57    Made Shot               Running Dunk Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              1     -9      6                    1               1  20201006  MIA  LAL
1   Shot Chart Detail  0041900404            151       2544  LeBron James  1610612747  Los Angeles Lakers       2                 11                 23  Missed Shot                      Layup Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              3     32     15                    1               0  20201006  MIA  LAL
2   Shot Chart Detail  0041900404            155       2544  LeBron James  1610612747  Los Angeles Lakers       2                 10                 42  Missed Shot                  Jump Bank Shot  2PT Field Goal          Mid-Range   Left Side Center(LC)        16-24 ft.             20   -129    161                    1               0  20201006  MIA  LAL
3   Shot Chart Detail  0041900404            176       2544  LeBron James  1610612747  Los Angeles Lakers       2                  9                  6    Made Shot              Driving Layup Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              0      3      6                    1               1  20201006  MIA  LAL
4   Shot Chart Detail  0041900404            187       2544  LeBron James  1610612747  Los Angeles Lakers       2                  8                 48    Made Shot               Driving Dunk Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              1      5      9                    1               1  20201006  MIA  LAL
5   Shot Chart Detail  0041900404            204       2544  LeBron James  1610612747  Los Angeles Lakers       2                  7                 25  Missed Shot              Driving Layup Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              3     29     14                    1               0  20201006  MIA  LAL
6   Shot Chart Detail  0041900404            272       2544  LeBron James  1610612747  Los Angeles Lakers       2                  2                 10  Missed Shot              Driving Layup Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              2    -29     -1                    1               0  20201006  MIA  LAL
7   Shot Chart Detail  0041900404            296       2544  LeBron James  1610612747  Los Angeles Lakers       2                  1                  3  Missed Shot                       Jump Shot  2PT Field Goal          Mid-Range  Right Side Center(RC)        16-24 ft.             18     66    169                    1               0  20201006  MIA  LAL
8   Shot Chart Detail  0041900404            349       2544  LeBron James  1610612747  Los Angeles Lakers       3                  8                 18    Made Shot                Pullup Jump shot  3PT Field Goal  Above the Break 3              Center(C)          24+ ft.             28    -20    286                    1               1  20201006  MIA  LAL
9   Shot Chart Detail  0041900404            362       2544  LeBron James  1610612747  Los Angeles Lakers       3                  7                 22    Made Shot  Cutting Finger Roll Layup Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              2      5     28                    1               1  20201006  MIA  LAL
10  Shot Chart Detail  0041900404            367       2544  LeBron James  1610612747  Los Angeles Lakers       3                  6                 44    Made Shot                Pullup Jump shot  3PT Field Goal  Above the Break 3              Center(C)          24+ ft.             27     -9    272                    1               1  20201006  MIA  LAL
11  Shot Chart Detail  0041900404            506       2544  LeBron James  1610612747  Los Angeles Lakers       4                  8                 47    Made Shot        Turnaround Fadeaway shot  2PT Field Goal          Mid-Range           Left Side(L)         8-16 ft.             13   -131     31                    1               1  20201006  MIA  LAL
12  Shot Chart Detail  0041900404            533       2544  LeBron James  1610612747  Los Angeles Lakers       4                  6                  8    Made Shot              Driving Layup Shot  2PT Field Goal    Restricted Area              Center(C)  Less Than 8 ft.              3    -28     28                    1               1  20201006  MIA  LAL
13  Shot Chart Detail  0041900404            540       2544  LeBron James  1610612747  Los Angeles Lakers       4                  5                 37  Missed Shot                Pullup Jump shot  3PT Field Goal  Above the Break 3   Left Side Center(LC)          24+ ft.             30   -131    274                    1               0  20201006  MIA  LAL
14  Shot Chart Detail  0041900404            548       2544  LeBron James  1610612747  Los Angeles Lakers       4                  4                 48  Missed Shot                Pullup Jump shot  3PT Field Goal  Above the Break 3   Left Side Center(LC)          24+ ft.             30    -98    286                    1               0  20201006  MIA  LAL
15  Shot Chart Detail  0041900404            568       2544  LeBron James  1610612747  Los Angeles Lakers       4                  3                 14  Missed Shot             Step Back Jump shot  3PT Field Goal  Above the Break 3   Left Side Center(LC)          24+ ft.             27   -168    217                    1               0  20201006  MIA  LAL
chitown88
  • 27,527
  • 4
  • 30
  • 59