python案例统计低位防守解围次数多少?

wen python案例 1

我来为您提供一个统计低位防守解围次数的Python案例,这个案例将模拟足球比赛中的防守数据。

python案例统计低位防守解围次数多少?

import pandas as pd
import numpy as np
from datetime import datetime
class DefenseStatsAnalyzer:
    """低位防守解围次数统计分析器"""
    def __init__(self):
        self.defense_data = []
    def generate_sample_data(self, num_matches=10):
        """生成模拟的防守数据"""
        teams = ['曼联', '利物浦', '阿森纳', '曼城', '切尔西']
        positions = ['中后卫', '边后卫', '后腰', '门将']
        for match_id in range(1, num_matches + 1):
            for player_idx in range(5):  # 每场5名防守球员
                data = {
                    'match_id': match_id,
                    'date': datetime(2024, 1, 1) + pd.Timedelta(days=match_id*7),
                    'team': np.random.choice(teams),
                    'player': f'球员{player_idx+1}',
                    'position': np.random.choice(positions),
                    'clearance_count': np.random.randint(0, 15),  # 解围次数
                    'low_block_clearance': np.random.randint(0, 10),  # 低位防守解围
                    'minutes_played': np.random.randint(60, 95),  # 出场时间
                    'opponent_attacks': np.random.randint(5, 30)  # 对手进攻次数
                }
                self.defense_data.append(data)
        return pd.DataFrame(self.defense_data)
    def calculate_low_block_clearance_stats(self, df):
        """计算低位防守解围统计"""
        stats = {
            'total_low_block_clearance': df['low_block_clearance'].sum(),
            'avg_low_block_clearance_per_match': df.groupby('match_id')['low_block_clearance'].sum().mean(),
            'avg_low_block_clearance_per_player': df['low_block_clearance'].mean(),
            'max_low_block_clearance': df['low_block_clearance'].max(),
            'min_low_block_clearance': df['low_block_clearance'].min()
        }
        return stats
    def analyze_by_position(self, df):
        """按位置分析低位防守解围"""
        position_stats = df.groupby('position')['low_block_clearance'].agg(['sum', 'mean', 'max'])
        return position_stats
    def analyze_by_team(self, df):
        """按球队分析低位防守解围"""
        team_stats = df.groupby('team')['low_block_clearance'].agg(['sum', 'mean', 'count'])
        return team_stats
    def identify_top_performers(self, df, top_n=5):
        """找出表现最好的防守球员"""
        player_stats = df.groupby(['player', 'position'])['low_block_clearance'].agg(['sum', 'mean']).reset_index()
        top_performers = player_stats.nlargest(top_n, 'mean')
        return top_performers
    def visualize_defense_stats(self, df):
        """可视化防守统计数据"""
        import matplotlib.pyplot as plt
        fig, axes = plt.subplots(2, 2, figsize=(15, 10))
        # 1. 每场比赛的低位防守解围趋势
        match_stats = df.groupby('match_id')['low_block_clearance'].sum()
        axes[0, 0].plot(match_stats.index, match_stats.values, marker='o')
        axes[0, 0].set_title('每场比赛低位防守解围趋势')
        axes[0, 0].set_xlabel('比赛编号')
        axes[0, 0].set_ylabel('解围次数')
        # 2. 不同位置的平均解围次数
        position_stats = df.groupby('position')['low_block_clearance'].mean().sort_values()
        axes[0, 1].barh(position_stats.index, position_stats.values)
        axes[0, 1].set_title('不同位置平均解围次数')
        axes[0, 1].set_xlabel('平均解围次数')
        # 3. 各球队总解围次数
        team_stats = df.groupby('team')['low_block_clearance'].sum().sort_values()
        axes[1, 0].bar(team_stats.index, team_stats.values)
        axes[1, 0].set_title('各球队总解围次数')
        axes[1, 0].set_xlabel('球队')
        axes[1, 0].set_ylabel('总解围次数')
        plt.setp(axes[1, 0].xaxis.get_majorticklabels(), rotation=45)
        # 4. 解围次数分布
        axes[1, 1].hist(df['low_block_clearance'], bins=15, edgecolor='black')
        axes[1, 1].set_title('解围次数分布')
        axes[1, 1].set_xlabel('解围次数')
        axes[1, 1].set_ylabel('频率')
        plt.tight_layout()
        plt.show()
    def generate_report(self, df):
        """生成详细报告"""
        print("="*60)
        print("低位防守解围分析报告")
        print("="*60)
        # 总体统计
        total_clearances = df['low_block_clearance'].sum()
        avg_clearances = df['low_block_clearance'].mean()
        print(f"\n1. 总体统计:")
        print(f"   - 总解围次数: {total_clearances}次")
        print(f"   - 平均每场解围: {avg_clearances:.1f}次")
        print(f"   - 场均解围次数: {df.groupby('match_id')['low_block_clearance'].sum().mean():.1f}次")
        # 位置统计
        print(f"\n2. 位置分析:")
        position_stats = self.analyze_by_position(df)
        for position in position_stats.index:
            print(f"   - {position}: 总计{position_stats.loc[position, 'sum']:.0f}次, "
                  f"平均{position_stats.loc[position, 'mean']:.1f}次, "
                  f"最高{position_stats.loc[position, 'max']:.0f}次")
        # 球队统计
        print(f"\n3. 球队分析:")
        team_stats = self.analyze_by_team(df)
        for team in team_stats.index:
            print(f"   - {team}: 总计{team_stats.loc[team, 'sum']:.0f}次, "
                  f"平均每场{team_stats.loc[team, 'mean']:.1f}次")
        # 最佳球员
        print(f"\n4. 最佳防守球员TOP5:")
        top_performers = self.identify_top_performers(df)
        for idx, (_, player) in enumerate(top_performers.iterrows(), 1):
            print(f"   {idx}. {player['player']} ({player['position']}): "
                  f"累计{player['sum']:.0f}次, 场均{player['mean']:.1f}次")
        # 关键指标
        print(f"\n5. 关键指标:")
        clearances_per_attack = df['low_block_clearance'].sum() / df['opponent_attacks'].sum()
        print(f"   - 解围效率(每百次对手进攻解围): {clearances_per_attack*100:.1f}%")
        print(f"   - 场均解围率: {df['low_block_clearance'].mean()/df['opponent_attacks'].mean()*100:.1f}%")
# 使用示例
def main():
    analyzer = DefenseStatsAnalyzer()
    # 生成模拟数据
    df = analyzer.generate_sample_data(num_matches=10)
    print("生成了模拟的防守数据...")
    print(f"数据条数: {len(df)}")
    print(f"涉及球队: {df['team'].unique()}")
    # 生成分析报告
    analyzer.generate_report(df)
    # 可视化
    analyzer.visualize_defense_stats(df)
    # 高级分析:找出解围效率最高的比赛
    print("\n6. 解围效率最高的比赛:")
    df['efficiency'] = df['low_block_clearance'] / df['minutes_played'] * 90  # 90分钟标准化
    top_efficiency_games = df.nlargest(5, 'efficiency')[['match_id', 'team', 'player', 'low_block_clearance', 'minutes_played', 'efficiency']]
    print(top_efficiency_games)
if __name__ == "__main__":
    main()

主要功能说明:

  1. 数据统计

    • 总解围次数
    • 场均解围次数
    • 按位置、球队进行分类统计
    • 球员个人表现排名
  2. 分析方法

    • 按位置分析(中后卫、边后卫、后腰、门将)
    • 按球队分析
    • 时间趋势分析
    • 效率指标计算
  3. 可视化展示

    • 比赛趋势图
    • 位置对比图
    • 球队对比图
    • 分布直方图
  4. 输出报告

    • 详细文本报告
    • 关键绩效指标
    • 最佳球员排名

运行这个程序会生成模拟数据,进行统计分析,并提供直观的可视化结果,您可以根据实际需求修改数据生成逻辑来适配真实比赛数据。

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