Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from nba_api.stats.endpoints import leaguegamefinder, boxscoretraditionalv2
- import pandas as pd
- import time
- class CelticsStats:
- def __init__(self, team_id='1610612738', start_date='2024-10-22', season_id='22024'):
- """
- Inizializza l'oggetto per gestire le statistiche dei Boston Celtics.
- :param team_id: ID della squadra (default: Boston Celtics).
- :param start_date: Data di inizio per filtrare le partite.
- :param season_id: ID della stagione NBA (es: '22024' per la stagione 2024-2025).
- """
- self.team_id = team_id
- self.start_date = start_date
- self.season_id = season_id
- self.season_games = None
- self.team_stats = []
- self.top_scorers = []
- self.wins = 0
- self.losses = 0
- def fetch_games(self):
- """Scarica i dati delle partite della stagione specificata e li filtra."""
- gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=self.team_id)
- games = gamefinder.get_data_frames()[0]
- # Filtrare le partite della stagione e dopo la data di inizio
- self.season_games = games[
- (games['SEASON_ID'] == self.season_id) &
- (games['GAME_DATE'] >= self.start_date)
- ].sort_values('GAME_DATE')
- # Selezionare colonne rilevanti
- self.season_games = self.season_games[['GAME_ID', 'GAME_DATE', 'MATCHUP', 'WL', 'PTS', 'PLUS_MINUS']]
- self.season_games.reset_index(drop=True, inplace=True)
- self.season_games.index += 1 # La colonna di indice parte da 1
- def process_games(self):
- """Elabora le partite, calcolando statistiche di squadra e il miglior marcatore."""
- for index, row in self.season_games.iterrows():
- game_id = row['GAME_ID']
- matchup = row['MATCHUP']
- game_date = row['GAME_DATE']
- result = row['WL']
- points = row['PTS']
- # Incrementare W-L
- if result == 'W':
- self.wins += 1
- else:
- self.losses += 1
- w_l_record = f"{self.wins}-{self.losses}"
- # Recuperare le statistiche della partita
- boxscore = boxscoretraditionalv2.BoxScoreTraditionalV2(game_id=game_id)
- player_stats = boxscore.player_stats.get_data_frame()
- team_stats_boxscore = boxscore.team_stats.get_data_frame()
- # Ottenere il punteggio dell'altra squadra
- opponent_stats = team_stats_boxscore[team_stats_boxscore['TEAM_ABBREVIATION'] != 'BOS']
- opponent_points = opponent_stats['PTS'].iloc[0]
- # Filtrare solo i giocatori dei Boston Celtics
- celtics_stats = player_stats[player_stats['TEAM_ABBREVIATION'] == 'BOS']
- # Calcolare statistiche di squadra
- team_fg_pct = celtics_stats['FG_PCT'].mean() * 100 if not celtics_stats['FG_PCT'].isna().all() else 0
- team_2pt_attempts = celtics_stats['FGA'] - celtics_stats['FG3A']
- team_2pt_made = celtics_stats['FGM'] - celtics_stats['FG3M']
- team_2pt_pct = (team_2pt_made.sum() / team_2pt_attempts.sum()) * 100 if team_2pt_attempts.sum() > 0 else 0
- team_3pt_pct = celtics_stats['FG3_PCT'].mean() * 100 if not celtics_stats['FG3_PCT'].isna().all() else 0
- team_ft_pct = celtics_stats['FT_PCT'].mean() * 100 if not celtics_stats['FT_PCT'].isna().all() else 0
- team_reb = celtics_stats['REB'].sum()
- team_ast = celtics_stats['AST'].sum()
- team_tov = celtics_stats['TO'].sum()
- team_stl = celtics_stats['STL'].sum()
- # Aggiungere statistiche di squadra
- self.team_stats.append({
- 'GAME_DATE': game_date,
- 'MATCHUP': matchup,
- 'PTS_team': points,
- 'PTS_opponent': opponent_points,
- 'W_L': w_l_record,
- 'TEAM_FG%': team_fg_pct,
- 'TEAM_2PT%': team_2pt_pct,
- 'TEAM_3PT%': team_3pt_pct,
- 'TEAM_FT%': team_ft_pct,
- 'TEAM_REB': team_reb,
- 'TEAM_AST': team_ast,
- 'TEAM_TOV': team_tov,
- 'TEAM_STL': team_stl
- })
- # Trovare il miglior marcatore
- top_scorer = celtics_stats.loc[celtics_stats['PTS'].idxmax()]
- self.top_scorers.append({
- 'GAME_DATE': game_date,
- 'MATCHUP': matchup,
- 'PLAYER_NAME': top_scorer['PLAYER_NAME'],
- 'PTS_player': top_scorer['PTS']
- })
- # Pausa per evitare di sovraccaricare l'API
- time.sleep(1)
- def get_final_dataframe(self):
- """Crea un DataFrame finale combinando statistiche di squadra e migliori marcatori."""
- team_stats_df = pd.DataFrame(self.team_stats)
- top_scorers_df = pd.DataFrame(self.top_scorers)
- final_df = pd.merge(
- team_stats_df,
- top_scorers_df,
- on=['GAME_DATE', 'MATCHUP'],
- suffixes=('_team', '_player')
- )
- return final_df
- def display_results(self):
- """Mostra i risultati finali."""
- final_df = self.get_final_dataframe()
- print("\nStatistiche di squadra e migliori marcatori:")
- print(final_df[['GAME_DATE', 'MATCHUP', 'PTS_team', 'PTS_opponent', 'W_L', 'TEAM_FG%', 'TEAM_2PT%',
- 'TEAM_3PT%', 'TEAM_FT%', 'TEAM_REB', 'TEAM_AST', 'TEAM_TOV',
- 'TEAM_STL', 'PLAYER_NAME', 'PTS_player']])
- # Esempio di utilizzo
- if __name__ == "__main__":
- celtics_stats = CelticsStats()
- celtics_stats.fetch_games()
- celtics_stats.process_games()
- celtics_stats.display_results()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement