Search code examples
pythonpandasdataframenba-api

Value Error Mismatch While Converting Using Pandas


here is the mismatch error I keep getting. I'm inputting "202710".

Traceback (most recent call last):
  File "nbastatsrecieveit.py", line 29, in <module>
    df.columns = headers
  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

To be honest, I'm not sure as to how to go about fixing this problem as it works with specific player IDs but not all of then. Here is the rest of my code:

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

print('Player ID?')
playerid = input()

filename = str(playerid) + '.xlsx'

response = shotchartdetail.ShotChartDetail(
    team_id= 0,
    context_measure_simple = 'FGA',
    #last_n_games = numGames,
    game_id_nullable = '0041900403',
    player_id= playerid
)

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 = pd.DataFrame(rows)
df.columns = headers

# write to excel file
df.to_excel(filename, index=False)

Solution

  • This is because your df is empty for ID 202710. Exception handling will resolve the issue here-

    df = pd.DataFrame(rows)
    try:
        df.columns = headers
    except:
        pass