Search code examples
pythonnba-api

How to get nba shot chart data correctly?


I want to get data from nba site to create shot chart. I get it from this site https://datavizardry.com/2020/01/28/nba-shot-charts-part-1/?fbclid=IwAR3BheHQkSAmCJRr_z7ux1ygbspLjLdrvTRjWAVHOrr2BPvVh7jsIos_e9w and my code looks like this:

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

response = shotchartdetail.ShotChartDetail(
    team_id=0,
    player_id=0,
    season_nullable='2001-02',
    season_type_all_star='Regular Season'
)

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

results = content['resultSets'][0]
headers = results['headers']
rows = results['rowSet']
df = pd.DataFrame(rows)
df.columns = headers

# write to csv file
df.to_csv(r'C:\Users\Comp\Desktop\nba_2001-02.csv', index=False)

It is working but in this article when I download example data from the beginning, the Author in data gets info about missed shots too, when I run my code I get only data about shots made. Is it possible to get info about missed shots too or nba not shares this data anymore?


Solution

  • The package by default (likely its been updated since the article) is set to only return shots where a point was scored, so you need to change that parameter to not be points, but rather field goal attempts, since that will return made and missed shots:

    response = shotchartdetail.ShotChartDetail(
        team_id=0,
        player_id=0,
        season_nullable='2001-02',
        context_measure_simple = 'FGA', #<-- Default is 'PTS' and will only return made shots, but we want all shot attempts
        season_type_all_star='Regular Season'
    )
    

    also, I'd add one more thing into the dataframe, so that you have the columns by name, as opposed to a number:

    results = content['resultSets'][0]
    headers = results['headers']
    rows = results['rowSet']
    df = pd.DataFrame(rows, columns=headers) #<-- add the columns parameter
    df.columns = headers