python案例统计赛季累计数据对比如何?

wen python案例 5

本文目录导读:

python案例统计赛季累计数据对比如何?

  1. 完整案例:NBA/篮球赛季数据统计对比
  2. 核心功能亮点
  3. 使用场景
  4. 扩展建议

我来提供一个完整的Python案例,用于统计和对比不同球员的赛季累计数据。

完整案例:NBA/篮球赛季数据统计对比

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
class SeasonStatsAnalyzer:
    """赛季数据统计分析器"""
    def __init__(self):
        self.data = None
        self.players = []
    def generate_sample_data(self, num_players=5, games_per_season=20):
        """生成模拟数据"""
        np.random.seed(42)
        players_demo = [
            ('张三', 1995, '后卫'),
            ('李四', 1998, '前锋'),
            ('王五', 1996, '中锋'),
            ('赵六', 1999, '后卫'),
            ('钱七', 1997, '前锋')
        ]
        seasons = ['2022-2023', '2023-2024', '2024-2025']
        data_rows = []
        for player_name, birth_year, position in players_demo[:num_players]:
            # 基础能力参数
            base_scoring = np.random.randint(15, 30)
            base_rebound = np.random.randint(3, 12)
            base_assist = np.random.randint(2, 8)
            for season in seasons:
                games = games_per_season
                # 生成每场比赛数据
                for game in range(games):
                    # 数据随时间趋势变化
                    trend_factor = 1 + (game / games) * np.random.normal(0.5, 0.2)
                    points = max(0, round(base_scoring * trend_factor + np.random.normal(3, 5)))
                    rebounds = max(0, round(base_rebound * trend_factor + np.random.normal(1, 2)))
                    assists = max(0, round(base_assist * trend_factor + np.random.normal(1, 2)))
                    data_rows.append({
                        'player': player_name,
                        'birth_year': birth_year,
                        'position': position,
                        'season': season,
                        'game_num': game + 1,
                        'points': points,
                        'rebounds': rebounds,
                        'assists': assists,
                        'turnovers': np.random.randint(0, 5),
                        'minutes': np.random.randint(20, 40)
                    })
        self.data = pd.DataFrame(data_rows)
        return self.data
    def load_data(self, file_path):
        """从文件加载数据"""
        try:
            self.data = pd.read_csv(file_path)
            return True
        except:
            print("数据加载失败")
            return False
    def calculate_season_totals(self, player_names=None):
        """计算赛季累计数据"""
        if self.data is None:
            return None
        df = self.data.copy()
        # 筛选球员
        if player_names:
            df = df[df['player'].isin(player_names)]
        # 计算赛季累计
        season_totals = df.groupby(['player', 'season']).agg({
            'points': 'sum',
            'rebounds': 'sum',
            'assists': 'sum',
            'turnovers': 'sum',
            'minutes': 'sum',
            'game_num': 'max'  # 比赛场次
        }).rename(columns={
            'points': '总得分',
            'rebounds': '总篮板',
            'assists': '总助攻',
            'turnovers': '总失误',
            'minutes': '总时间',
            'game_num': '比赛场次'
        }).reset_index()
        # 计算场均数据
        season_totals['场均得分'] = season_totals['总得分'] / season_totals['比赛场次']
        season_totals['场均篮板'] = season_totals['总篮板'] / season_totals['比赛场次']
        season_totals['场均助攻'] = season_totals['总助攻'] / season_totals['比赛场次']
        return season_totals
    def compare_players(self, player_selection=None, stat='场均得分'):
        """对比球员数据"""
        totals = self.calculate_season_totals(player_selection)
        if totals is None:
            print("没有数据可供分析")
            return None
        # 透视表格式
        pivot_df = totals.pivot(index='season', columns='player', values=stat)
        return pivot_df
    def plot_comparison(self, stat='场均得分'):
        """绘制数据对比图"""
        pivot_df = self.compare_players(stat=stat)
        if pivot_df is None or pivot_df.empty:
            print("没有数据可以绘图")
            return
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
        # 赛季趋势比较
        pivot_df.plot(kind='line', marker='o', ax=ax1, linewidth=2)
        ax1.set_title(f'球员{stat}赛季趋势对比')
        ax1.set_xlabel('赛季')
        ax1.set_ylabel(stat)
        ax1.legend(title='球员')
        ax1.grid(True, alpha=0.3)
        # 赛季总览对比
        totals = self.calculate_season_totals()
        latest_season = totals['season'].max()
        latest_data = totals[totals['season'] == latest_season]
        # 柱状图
        x = np.arange(len(latest_data['player']))
        width = 0.15
        points = latest_data['总得分']
        rebounds = latest_data['总篮板'] * 2  # 缩放以便可视化比较
        assists = latest_data['总助攻'] * 3
        bars1 = ax2.bar(x - width, points, width, label='总得分', color='crimson')
        bars2 = ax2.bar(x, rebounds, width, label='总篮板(×2)', color='navy')
        bars3 = ax2.bar(x + width, assists, width, label='总助攻(×3)', color='green')
        ax2.set_title(f'{latest_season}赛季球员累计数据对比')
        ax2.set_xlabel('球员')
        ax2.set_ylabel('累计数值')
        ax2.set_xticks(x)
        ax2.set_xticklabels(latest_data['player'])
        ax2.legend()
        ax2.grid(True, alpha=0.3)
        # 添加数据标签
        for bars in [bars1, bars2, bars3]:
            for bar in bars:
                height = bar.get_height()
                ax2.text(bar.get_x() + bar.get_width()/2., height,
                        f'{height:.0f}',
                        ha='center', va='bottom', fontsize=8)
        plt.tight_layout()
        plt.show()
    def comprehensive_report(self, player_names=None):
        """生成综合报告"""
        totals = self.calculate_season_totals(player_names)
        if totals is None:
            return None
        report = {
            '总得分榜': totals.nlargest(5, '总得分')[['player', 'season', '总得分']],
            '场均得分榜': totals.nlargest(5, '场均得分')[['player', 'season', '场均得分']],
            '总篮板榜': totals.nlargest(5, '总篮板')[['player', 'season', '总篮板']],
            '总助攻榜': totals.nlargest(5, '总助攻')[['player', 'season', '总助攻']]
        }
        return report
    def performance_trend_analysis(self, player_names=None):
        """分析球员表现趋势"""
        if self.data is None:
            return None
        df = self.data.copy()
        if player_names:
            df = df[df['player'].isin(player_names)]
        # 计算滚动平均
        df['滚动均分'] = df.groupby(['player', 'season'])['points'].transform(
            lambda x: x.expanding().mean()
        )
        # 计算进步/退步幅度
        comparison = df.groupby(['player', 'season']).agg({
            'points': 'sum',
            'game_num': 'max'
        }).reset_index()
        comparison['场均得分'] = comparison['points'] / comparison['game_num']
        # 赛季间对比
        pivot = comparison.pivot(index='player', columns='season', values='场均得分')
        # 计算变化
        change_cols = []
        seasons = pivot.columns.tolist()
        for i in range(1, len(seasons)):
            col_name = f'{seasons[i-1]}→{seasons[i]}变化'
            pivot[col_name] = pivot[seasons[i]] - pivot[seasons[i-1]]
            change_cols.append(col_name)
        return pivot[change_cols]
# 主程序
def main():
    print("=== 赛季数据统计对比系统 ===")
    # 创建分析器
    analyzer = SeasonStatsAnalyzer()
    # 生成示例数据
    print("正在生成模拟数据...")
    analyzer.generate_sample_data(num_players=5, games_per_season=20)
    # 显示数据概要
    print("\n数据概要:")
    print(f"总记录数: {len(analyzer.data)}")
    print(f"球员列表: {analyzer.data['player'].unique().tolist()}")
    print(f"赛季列表: {analyzer.data['season'].unique().tolist()}")
    # 计算赛季累计数据
    print("\n=== 赛季累计数据 ===")
    season_totals = analyzer.calculate_season_totals()
    print(season_totals.to_string(index=False))
    # 绘制对比图
    print("\n正在生成对比图表...")
    analyzer.plot_comparison('场均得分')
    # 显示排行报告
    print("\n=== 综合排名 ===")
    report = analyzer.comprehensive_report()
    for title, df in report.items():
        print(f"\n{title}:")
        print(df.to_string(index=False))
    # 趋势分析
    print("\n=== 赛季进步/退步分析 ===")
    trend_analysis = analyzer.performance_trend_analysis()
    if trend_analysis is not None:
        print(trend_analysis.to_string())
    # 导出数据
    print("\n正在导出数据...")
    season_totals.to_csv('season_totals.csv', index=False, encoding='utf-8-sig')
    print("数据已导出至 season_totals.csv")
if __name__ == "__main__":
    main()

核心功能亮点

数据模拟与加载

  • 自动生成多赛季、多球员的比赛数据
  • 支持从CSV文件加载真实数据

累计统计功能

  • 计算总得分、总篮板、总助攻等累计数据
  • 自动计算场均数据
  • 支持多赛季对比

可视化对比

  • 赛季趋势折线图
  • 球员累计数据柱状图
  • 多维度排名视图

高级分析

  • 球员间数据交互对比
  • 赛季进步/退步分析
  • 综合排名报告

使用场景

  1. 球员评估:评估不同球员的赛季表现
  2. 选秀分析:对比新秀赛季数据趋势
  3. 战术调整:分析不同位置的攻防数据
  4. 商业决策:评估球员的持续表现能力

扩展建议

# 1. 增加位置权重对比
def position_weighted_compare(self):
    """按位置权重对比"""
    weights = {'后卫': 1.0, '前锋': 1.2, '中锋': 1.4}
    self.data['weighted_points'] = self.data.apply(
        lambda x: x['points'] * weights.get(x['position'], 1), axis=1
    )
# 2. 增加效率值分析
def calculate_efficiency(self):
    """计算球员效率值"""
    self.data['efficiency'] = (
        self.data['points'] + 
        self.data['rebounds'] + 
        self.data['assists'] * 1.5 -
        self.data['turnovers']
    )

这个案例提供了完整的赛季数据统计对比解决方案,既适合学习也适合实际应用,你可以根据具体需求调整数据结构和分析维度。

抱歉,评论功能暂时关闭!