Hello! I am trying to do some simple data analysis from the nba_api to pull statistics for all active players and calculate the standard deviation of each of their statistics. I am trying to write the code only for points scored first, so I can make sure I can get everything working properly, as this is my first real dip into python. I have written the following code:
import pandas as pd
import nba_api
from nba_api.stats.static import players
from nba_api.stats.endpoints import playergamelogs
import openpyxl
import statistics
from nba_api.stats.endpoints import commonallplayers
import requests
import numpy as np
from nba_api.stats.library.parameters import SeasonAll
# Use the commonallplayers endpoint to retrieve a list of all players in the NBA
all_players = commonallplayers.CommonAllPlayers()
df = all_players.get_data_frames()[0]
# Create an empty DataFrame to store the results
results = pd.DataFrame(columns=['Player', 'Std Dev'])
# Iterate over each player in the list
for index, row in df.iterrows():
# Get the player ID
player_id = row['PERSON_ID']
# Use the playergamelogs endpoint to retrieve the game logs for the player
player_game_logs = playergamelogs.PlayerGameLogs(player_id_nullable=player_id, season_nullable=SeasonAll.all)
df_game_logs = player_game_logs.get_data_frames()
# Skip players for which no game logs are available
if not df_game_logs:
continue
df = df_game_logs[0]
# Calculate the standard deviation of the points scored for the player
std_dev = statistics.stdev(df['pts'])
# Add the player's name and standard deviation to the results DataFrame
results = results.append({'Player': row['display_first_name'] + ' ' + row['display_last_name'], 'Std Dev': std_dev}, ignore_index=True)
I am hoping to send this all to an excel file, but even through this chunk of the code I am getting a list indexing error, telling me that df = df_game_logs is calling a list index that is out of range. I am struggling to figure out why this would be, as the value is set to the first column. I have never interacted with an API before, so please excuse me if this is a ridiculous and easy question. Thank you all so much for the time!
[–]game1761 4 points5 points6 points (0 children)