|

|  How to Retrieve NBA Statistics with NBA API in Python

How to Retrieve NBA Statistics with NBA API in Python

October 31, 2024

Learn to access NBA stats using the NBA API in Python. This guide covers setup, coding examples, and tips for seamless data retrieval.

How to Retrieve NBA Statistics with NBA API in Python

 

Install the Required Libraries

 

  • To interact with the NBA API in Python, you'll need a library that supports HTTP requests, like `requests`. Also, installing `pandas` can help with structuring the data you'll retrieve from the API. Use the following pip commands to install them:

 

pip install requests pandas

 

Access NBA Statistics via API

 

  • While the NBA provides a public-facing API through their website, it doesn't have a direct public API with keys and oauth. Third-party libraries like `nba_api` make it easy to interact with their data. Install it with pip:

 

pip install nba_api

 

  • Here is an example of how you can use the `nba_api.stats.endpoints` module to retrieve player statistics:

 

from nba_api.stats.endpoints import playercareerstats
import pandas as pd

# Fetch career stats for a player by ID
career = playercareerstats.PlayerCareerStats(player_id='2544')  # LeBron James' player ID
career_data = career.get_data_frames()[0]

# Show the first few rows of the data
print(career_data.head())

 

Understanding Player IDs

 

  • Player IDs are often necessary when pulling data using the NBA API. The `nba_api` library provides a way to fetch player information, including their IDs:

 

from nba_api.stats.static import players

# Retrieve information for all NBA players
nba_players = players.get_players()

# Search for a player by name to get their ID
lebron = [player for player in nba_players if player['full_name'] == 'LeBron James'][0]
print(f"LeBron James' player ID: {lebron['id']}")

 

Fetching Game Stats

 

  • To fetch statistics for games, you might use the `gamefinder` endpoint. This retrieves comprehensive game-related statistics:

 

from nba_api.stats.endpoints import leaguegamefinder

# Get all games for a specific season for a player
gamefinder = leaguegamefinder.LeagueGameFinder(player_id_nullable='2544')
games = gamefinder.get_data_frames()[0]

# Output the first few games
print(games.head())

 

Handling API Rate Limits and Data Parsing

 

  • When using the NBA's unofficial JSON API, it's essential to consider API rate limits. If you receive HTTP error 429, it indicates your script is making too many requests in a short period. Implement a sleep function:

 

import time
from nba_api.stats.endpoints import playergamelog

# Fetch the game log for a player
gamelog = playergamelog.PlayerGameLog(player_id='2544')
time.sleep(2)  # Wait for 2 seconds to respect endpoint limits
gamelog_data = gamelog.get_data_frames()[0]

print(gamelog_data.head())

 

  • Additionally, parse the data directly into a `pandas` DataFrame for easier manipulation and analysis. The `nba_api` already outputs as a DataFrame, which makes data handling straightforward.

 

Export Data for Analysis

 

  • Finally, to facilitate further analysis or sharing of the data, consider exporting it to a CSV file:

 

career_data.to_csv('lebron_james_career_stats.csv', index=False)

 

By following these steps, you can efficiently gather NBA statistics using Python and the unofficial NBA API, leveraging useful libraries and handling data in a structured way suitable for analysis.

Pre-order Friend AI Necklace

Pre-Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action

team@basedhardware.com

company

careers

invest

privacy

products

omi

omi dev kit

personas

resources

apps

affiliate

docs

github

help