import tkinter as tk
from tkinter import ttk
import time
import pandas as pd
Precomputed dictionary of team names to abbreviations
TEAM_ABBR = {
"Arizona Cardinals": "ARI",
"Atlanta Falcons": "ATL",
"Baltimore Ravens": "BAL",
"Buffalo Bills": "BUF",
"Carolina Panthers": "CAR",
"Chicago Bears": "CHI",
"Cincinnati Bengals": "CIN",
"Cleveland Browns": "CLE",
"Dallas Cowboys": "DAL",
"Denver Broncos": "DEN",
"Detroit Lions": "DET",
"Green Bay Packers": "GB",
"Houston Texans": "HOU",
"Indianapolis Colts": "IND",
"Jacksonville Jaguars": "JAX",
"Kansas City Chiefs": "KC",
"Las Vegas Raiders": "LV",
"Los Angeles Chargers": "LAC",
"Los Angeles Rams": "LA", # Note: Adjusted abbreviation
"Miami Dolphins": "MIA",
"Minnesota Vikings": "MIN",
"New England Patriots": "NE",
"New Orleans Saints": "NO",
"New York Giants": "NYG",
"New York Jets": "NYJ",
"Philadelphia Eagles": "PHI",
"Pittsburgh Steelers": "PIT",
"San Francisco 49ers": "SF",
"Seattle Seahawks": "SEA",
"Tampa Bay Buccaneers": "TB",
"Tennessee Titans": "TEN",
"Washington Commanders": "WAS"
}
def get_top_players_for_selected_teams(selected_teams, selected_stat, consistency_threshold, apply_consistency_filter, use_lowest_score):
# Map selected team names to team abbreviations
selected_team_abbr = [TEAM_ABBR[team] for team in selected_teams]
code
Assistant
# Fetch weekly data for the current season or seasons
NFL_SEASONS = [2022] # Adjust this to the desired season(s)
try:
# Read weekly data from a CSV file (you need to adjust the URL or file name if necessary)
url = 'https://github.com/leesharpe/nfldata/raw/master/data/player_game.csv'
full_weekly_data = pd.read_csv(url, low_memory=False)
weekly_data = full_weekly_data[full_weekly_data['season'].isin(NFL_SEASONS)]
except Exception as e:
print(f"Failed to fetch weekly data: {e}")
return []
# Filter players from selected teams
filtered_players = weekly_data[weekly_data['team'].isin(selected_team_abbr)]
# Map selected_stat to the corresponding column in weekly_data
stat_column_map = {'Rushing Yards': 'rush_yds', 'Receiving Yards': 'rec_yds', 'Receptions': 'rec'}
stat_column = stat_column_map.get(selected_stat)
if stat_column is None:
print(f"Stat {selected_stat} not available.")
return []
# Group data by player
player_stats = filtered_players.groupby('player_id')
# Prepare a list to store player statistics
all_player_stats = []
for player_id, group in player_stats:
player_name = group['player'].iloc[0]
team = group['team'].iloc[0]
season = group['season'].iloc[0]
games_played = group['week'].nunique()
stat_values = group[stat_column].fillna(0)
if stat_values.sum() == 0:
continue # Skip players with no stats
if use_lowest_score:
stat_value = stat_values.min()
else:
stat_value = stat_values.mean()
if apply_consistency_filter:
std_dev = stat_values.std()
if pd.isna(std_dev) or std_dev > consistency_threshold:
continue # Skip player if standard deviation exceeds threshold
else:
std_dev = None
all_player_stats.append((team, player_name, season, stat_value, std_dev, games_played))
# Remove players with missing stat_value
all_player_stats = [x for x in all_player_stats if pd.notnull(x[3]) and x[3] != float('inf')]
# Return sorted results by stat_value
return sorted(all_player_stats, key=lambda x: x[3], reverse=not use_lowest_score)
def display_top_players():
selected_teams = [team_listbox.get(i) for i in team_listbox.curselection()]
selected_stat_value = selected_stat.get()
try:
max_players = int(max_players_entry.get())
except ValueError:
result_label.config(text="Invalid number for max players.")
return
try:
consistency_threshold = float(consistency_entry.get())
except ValueError:
result_label.config(text="Invalid number for consistency threshold.")
return
code
apply_consistency_filter = consistency_var.get()
use_lowest_score = lowest_score_var.get()
if not selected_teams:
result_label.config(text="Please select at least one team.")
return
result_label.config(text="Fetching data...")
root.update() # Refresh UI during processing
start_time = time.time()
top_players = get_top_players_for_selected_teams(
selected_teams, selected_stat_value, consistency_threshold,
apply_consistency_filter, use_lowest_score
)[:max_players]
end_time = time.time()
# Display results
result_area.delete("1.0", tk.END)
if not top_players:
result_label.config(text="No top players found.")
return
result_label.config(text=f"Data fetched successfully in {end_time - start_time:.2f} seconds!")
# Determine the appropriate label for the stat
stat_label_map = {'Rushing Yards': 'Rushing Yards', 'Receiving Yards': 'Receiving Yards', 'Receptions': 'Receptions'}
stat_label_text = stat_label_map.get(selected_stat_value, 'Stat')
if use_lowest_score:
result_area.insert(tk.END, f"Top {len(top_players)} players based on lowest {stat_label_text} per game:\n")
else:
result_area.insert(tk.END, f"Top {len(top_players)} players based on average {stat_label_text} per game:\n")
result_text = ""
for i, (team, player, season, stat_value, std_dev, games_played) in enumerate(top_players, start=1):
stat_line = f"{i}. {player} - {stat_value:.2f} {stat_label_text} per game (Games Played: {games_played})"
if apply_consistency_filter and std_dev is not None:
stat_line += f" (Std Dev: {std_dev:.2f})"
stat_line += f" ({season} season) [{team}]"
result_text += stat_line + "\n"
result_area.insert(tk.END, result_text + "\n")
Certainly! Let's work on fixing your script. It appears that there are a few potential issues:
Data Source Availability and Format:
The CSV file you're trying to download might have changed in structure or content.
Column names in the CSV might be different from those used in your script.
Team Abbreviations:
The abbreviations in your TEAM_ABBR dictionary might not match those in the data.
For example, "Los Angeles Rams" abbreviation is "LAR" in most data sources, not "LA".
Statistical Calculations:
The statistics you're trying to compute might not be present or might have different column names.
For instance, the column for rushing yards might be named differently in the dataset.
Season Data Availability:
The dataset might not contain data for the 2022 season as expected.
GUI Updates:
The GUI might need to be updated to reflect any changes made to the data processing.
Let's address each issue step by step:
1. Verify and Update Data Source
First, let's check if the data source is accessible and whether the columns match what your script expects.
python
import pandas as pd
url = 'https://github.com/leesharpe/nfldata/raw/master/data/player_game.csv'
try:
full_weekly_data = pd.read_csv(url, low_memory=False)
print(full_weekly_data.columns)
except Exception as e:
print(f"Failed to fetch weekly data: {e}")
Action:
Run the above code snippet to print out all the columns in the dataset.
This will help us verify the actual column names.
Common Findings:
The columns might be named differently, such as 'rush_yds' might be 'rush_yards' or 'receiving_yards'.
The team column may be named 'recent_team' instead of 'team'.
Player names might be under 'player_name' instead of 'player'.
2. Update Column Names and Team Abbreviations
Based on the actual columns in the data, update your script accordingly.
Updated TEAM_ABBR Dictionary:
python
TEAM_ABBR = {
"Arizona Cardinals": "ARI",
"Atlanta Falcons": "ATL",
"Baltimore Ravens": "BAL",
"Buffalo Bills": "BUF",
"Carolina Panthers": "CAR",
"Chicago Bears": "CHI",
"Cincinnati Bengals": "CIN",
"Cleveland Browns": "CLE",
"Dallas Cowboys": "DAL",
"Denver Broncos": "DEN",
"Detroit Lions": "DET",
"Green Bay Packers": "GB",
"Houston Texans": "HOU",
"Indianapolis Colts": "IND",
"Jacksonville Jaguars": "JAX",
"Kansas City Chiefs": "KC",
"Las Vegas Raiders": "LV",
"Los Angeles Chargers": "LAC",
"Los Angeles Rams": "LAR", # Updated abbreviation
"Miami Dolphins": "MIA",
"Minnesota Vikings": "MIN",
"New England Patriots": "NE",
"New Orleans Saints": "NO",
"New York Giants": "NYG",
"New York Jets": "NYJ",
"Philadelphia Eagles": "PHI",
"Pittsburgh Steelers": "PIT",
"San Francisco 49ers": "SF",
"Seattle Seahawks": "SEA",
"Tampa Bay Buccaneers": "TB",
"Tennessee Titans": "TEN",
"Washington Commanders": "WAS"
}
Adjust Column Name Mapping:
Update the mapping according to the actual column names:
python
# Map selected_stat to the corresponding column in weekly_data
stat_column_map = {
'Rushing Yards': 'rush_yards', # Adjusted based on actual column name
'Receiving Yards': 'rec_yards', # Adjusted
'Receptions': 'receptions' # Adjusted
}
# Update column names if necessary
full_weekly_data.rename(columns={
'recent_team': 'team',
'player_name': 'player',
# Add more renamings if required
}, inplace=True)
Verify that the columns exist after renaming:
python
print(full_weekly_data.columns)
3. Update Season Data Availability
Check which seasons are available in the dataset:
python
print(full_weekly_data['season'].unique())
Action:
Adjust the NFL_SEASONS list accordingly.
python
NFL_SEASONS = [2021] # Use a season that is available in the data
4. Adjust the Statistical Calculations
Ensure that the statistical calculations in your script use the correct column names and handle missing data appropriately.
Modify the get_top_players_for_selected_teams function:
python
def get_top_players_for_selected_teams(selected_teams, selected_stat, consistency_threshold, apply_consistency_filter, use_lowest_score):
# Map selected team names to team abbreviations
selected_team_abbr = [TEAM_ABBR[team] for team in selected_teams]
# Fetch weekly data for the current season or seasons
NFL_SEASONS = [2021] # Adjust this to the desired season(s)
try:
# Read weekly data from a CSV file
url = 'https://github.com/leesharpe/nfldata/raw/master/data/player_game.csv'
full_weekly_data = pd.read_csv(url, low_memory=False)
# Rename columns if necessary
full_weekly_data.rename(columns={
'recent_team': 'team',
'player_name': 'player',
'rush_yards': 'rush_yds', # Adjusted column names
'rec_yards': 'rec_yds',
}, inplace=True)
weekly_data = full_weekly_data[full_weekly_data['season'].isin(NFL_SEASONS)]
except Exception as e:
print(f"Failed to fetch weekly data: {e}")
return []
# Filter players from selected teams
filtered_players = weekly_data[weekly_data['team'].isin(selected_team_abbr)]
# Map selected_stat to the corresponding column in weekly_data
stat_column_map = {'Rushing Yards': 'rush_yds', 'Receiving Yards': 'rec_yds', 'Receptions': 'receptions'} # Adjusted
stat_column = stat_column_map.get(selected_stat)
if stat_column is None:
print(f"Stat '{selected_stat}' not available.")
return []
# Group data by player
player_stats = filtered_players.groupby('player_id')
# Prepare a list to store player statistics
all_player_stats = []
for player_id, group in player_stats:
player_name = group['player'].iloc[0]
team = group['team'].iloc[0]
season = group['season'].iloc[0]
games_played = group['week'].nunique()
stat_values = group[stat_column].fillna(0)
if stat_values.sum() == 0:
continue # Skip players with no stats
if use_lowest_score:
stat_value = stat_values.min()
else:
stat_value = stat_values.mean()
if apply_consistency_filter:
std_dev = stat_values.std()
if pd.isna(std_dev) or std_dev > consistency_threshold:
continue # Skip player if standard deviation exceeds threshold
else:
std_dev = None
all_player_stats.append((team, player_name, season, stat_value, std_dev, games_played))
# Remove players with missing stat_value
all_player_stats = [
x for x in all_player_stats if pd.notnull(x[3]) and x[3] != float('inf') and x[3] != float('-inf')
]
# Return sorted results by stat_value
return sorted(all_player_stats, key=lambda x: x[3], reverse=not use_lowest_score)
5. Updating the GUI
Ensure that the GUI elements correspond to the updated data processing functions.
Keep the GUI code mostly the same.
Ensure that any variable names and function calls match the updated code.
Full Corrected Script
python
Final Notes
Make sure to test the script after making these changes.
If you encounter any errors, add print statements to debug and check variable values at different stages.
Ensure that the data being processed matches your expectations at each step.
Let me know if you encounter any further issues or if there's anything else I can assist you with!