Search code examples
pandaslistdataframenba-api

How do I convert NBA-API List to DataFrame


Having an issue converting NBA-API object to a DataFrame. What I get is a list of the dataframe. How do I pull the DataFrame out the list or skip the list and create the DataFrame.

## NBA API endpoints needed to obtain data
import nba_api.stats.endpoints
from nba_api.stats.static import players
from nba_api.stats.static import teams
from nba_api.stats.endpoints import shotchartdetail

import pandas as pd
from pandas import DataFrame
import matplotlib as mpl
import matplotlib.pyplot as plt

BBplayers = players.get_players()
BBteams = teams.get_teams()

print(type(players))
print(BBplayers[0])
print(len(BBplayers))
## LEN PLAYERS = 4501  PLAYER TYPE IS DICTIONARIES INSIDE LIST


Durant = [player for player in BBplayers if player['full_name'] == 'Kevin Durant'][0]
Durant_id = Durant['id']
print(Durant_id)
## Durant ID = 201142

Thunder = [name for name in BBteams if name['full_name']=='Oklahoma City Thunder'][0]
Thunder_id = Thunder['id']
print(Thunder_id)
print(type(Thunder_id))
## Thunder ID = 1610612760

DurantShotsChart = shotchartdetail.ShotChartDetail(player_id='201142',team_id=1610612760)

print(DurantShotsChart)

NewDF=DurantShotsChart.get_data_frames()

print(type(NewDF))
print(NewDF[1])
print(len(NewDF))

Solution

  • According to the API documentation you should get two dataframes. And since the get_data_frames method always outputs a list of DataFrames, you can retrieve them separately by indexing:

    league_averages = NewDF[0]
    

    Which has the columns ['GRID_TYPE', 'SHOT_ZONE_BASIC', 'SHOT_ZONE_AREA', 'SHOT_ZONE_RANGE', 'FGA', 'FGM', 'FG_PCT'].

    And then

    shot_chart_detail= NewDf[1]
    

    Which has the following columns ['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']