使用 Pandas 转换时值错误不匹配

Value Error Mismatch While Converting Using Pandas

这是我不断收到的不匹配错误。我正在输入“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

老实说,我不确定如何解决这个问题,因为它适用于特定玩家 ID,但不是所有玩家 ID。这是我的其余代码:

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)

这是因为您的 df 的 ID 202710 为空。异常处理将解决这里的问题-

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