Spaces:
Build error
Build error
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| import os | |
| # 載入所有年度的資料 | |
| def load_all_attendance_data(): | |
| all_data = [] | |
| for year in range(1994, 2025): # 1993–1994 到 2023–2024 | |
| filename = f"nba_attendance_{year-1}-{year}.csv" | |
| if os.path.exists(filename): | |
| df = pd.read_csv(filename) | |
| df["YEAR"] = f"{year-1}-{year}" | |
| all_data.append(df) | |
| return pd.concat(all_data, ignore_index=True) | |
| # 整合資料 | |
| df_all = load_all_attendance_data() | |
| # 整理球隊與年份選單 | |
| all_teams = sorted(df_all["TEAM"].unique()) | |
| all_years = sorted(df_all["YEAR"].unique()) | |
| # 主功能函式 | |
| def show_home_attendance(team, year): | |
| # 找出指定年份與球隊的主場總人數 | |
| record = df_all[(df_all["TEAM"] == team) & (df_all["YEAR"] == year)] | |
| if record.empty: | |
| return f"{team} 在 {year} 沒有資料", None | |
| total_attendance = record["HOME_TOTAL"].values[0] | |
| # 產生直條圖:該隊從 1993-94 到 2023-24 的 HOME_TOTAL 變化 | |
| team_data = df_all[df_all["TEAM"] == team] | |
| years = team_data["YEAR"] | |
| totals = pd.to_numeric(team_data["HOME_TOTAL"].str.replace(',', ''), errors='coerce') | |
| plt.figure(figsize=(10, 5)) | |
| plt.bar(years, totals) | |
| plt.title(f"{team} HOME_TOTAL Attendance Over Years") | |
| plt.xlabel("Season") | |
| plt.ylabel("HOME_TOTAL") | |
| plt.xticks(rotation=45) | |
| plt.tight_layout() | |
| # 將圖表轉為圖片傳回 | |
| return f"{team} 在 {year} 年的主場總人數為:{total_attendance}", plt.gcf() | |
| # Gradio 介面 | |
| interface = gr.Interface( | |
| fn=show_home_attendance, | |
| inputs=[ | |
| gr.Dropdown(choices=all_teams, label="選擇球隊"), | |
| gr.Dropdown(choices=all_years, label="選擇年份") | |
| ], | |
| outputs=[ | |
| gr.Textbox(label="主場總人數"), | |
| gr.Plot(label="歷年主場總人數變化") | |
| ], | |
| title="NBA 主場觀眾總人數查詢器", | |
| description="選擇一支球隊與一個年份,查看主場總觀眾人數,並呈現其歷年趨勢圖" | |
| ) | |
| interface.launch() | |