|

|  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.

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit 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 開発キット 2

無限のカスタマイズ

OMI 開発キット 2

$69.99

Omi AIネックレスで会話を音声化、文字起こし、要約。アクションリストやパーソナライズされたフィードバックを提供し、あなたの第二の脳となって考えや感情を語り合います。iOSとAndroidでご利用いただけます。

  • リアルタイムの会話の書き起こしと処理。
  • 行動項目、要約、思い出
  • Omi ペルソナと会話を活用できる何千ものコミュニティ アプリ

もっと詳しく知る

Omi Dev Kit 2: 新しいレベルのビルド

主な仕様

OMI 開発キット

OMI 開発キット 2

マイクロフォン

はい

はい

バッテリー

4日間(250mAH)

2日間(250mAH)

オンボードメモリ(携帯電話なしで動作)

いいえ

はい

スピーカー

いいえ

はい

プログラム可能なボタン

いいえ

はい

配送予定日

-

1週間

人々が言うこと

「記憶を助ける、

コミュニケーション

ビジネス/人生のパートナーと、

アイデアを捉え、解決する

聴覚チャレンジ」

ネイサン・サッズ

「このデバイスがあればいいのに

去年の夏

記録する

「会話」

クリスY.

「ADHDを治して

私を助けてくれた

整頓された。"

デビッド・ナイ

OMIネックレス:開発キット
脳を次のレベルへ

最新ニュース
フォローして最新情報をいち早く入手しましょう

最新ニュース
フォローして最新情報をいち早く入手しましょう

thought to action.

Based Hardware Inc.
81 Lafayette St, San Francisco, CA 94103
team@basedhardware.com / help@omi.me

Company

Careers

Invest

Privacy

Events

Manifesto

Compliance

Products

Omi

Wrist Band

Omi Apps

omi Dev Kit

omiGPT

Personas

Omi Glass

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

Ambassadors

Resellers

© 2025 Based Hardware. All rights reserved.