python案例统计高球传中争顶成功率?

wen python案例 5

本文目录导读:

python案例统计高球传中争顶成功率?

  1. 完整代码实现
  2. 使用示例
  3. 额外功能:进阶分析
  4. 运行示例

我来为您创建一个足球高球传中争顶成功率的统计案例。

完整代码实现

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
class HighBallStatAnalyzer:
    """高球传中争顶成功率分析器"""
    def __init__(self):
        """初始化数据容器"""
        self.data = []
        self.df = None
    def generate_sample_data(self, num_records=100):
        """生成示例数据"""
        np.random.seed(42)
        players = ['张伟', '李强', '王浩', '赵磊', '陈晨', 
                   '刘洋', '杨帆', '孙明', '周涛', '吴刚']
        positions = ['前锋', '中场', '后卫']
        matches = [f'第{i}轮' for i in range(1, 20)]
        for _ in range(num_records):
            record = {
                '球员': np.random.choice(players),
                '位置': np.random.choice(positions),
                '比赛': np.random.choice(matches),
                '传球方式': np.random.choice(['角球传中', '边路传中', '定位球', '任意球']),
                '传球区域': np.random.choice(['左路', '右路', '中路']),
                '比赛时间': np.random.randint(1, 95),
                '是否接触': np.random.choice([0, 1], p=[0.3, 0.7]),
                '争顶成功': np.random.choice([0, 1], p=[0.4, 0.6])
            }
            self.data.append(record)
        self.df = pd.DataFrame(self.data)
        return self.df
    def calculate_success_rate(self):
        """计算争顶成功率"""
        if self.df is None:
            return None
        df = self.df.copy()
        # 计算总体争顶成功率
        total_stats = {
            '总传中次数': len(df),
            '争顶次数': df['是否接触'].sum(),
            '争顶成功次数': df['争顶成功'].sum(),
            '总体成功率': df['争顶成功'].mean() * 100
        }
        # 按球员统计
        player_stats = df.groupby('球员').agg({
            '是否接触': ['count', 'sum'],
            '争顶成功': ['sum', 'mean']
        }).round(4)
        player_stats.columns = ['传中次数', '争顶次数', '争顶成功次数', '成功率']
        player_stats['成功率'] = player_stats['成功率'] * 100
        player_stats = player_stats.sort_values('成功率', ascending=False)
        # 按位置统计
        position_stats = df.groupby('位置').agg({
            '是否接触': ['count', 'sum'],
            '争顶成功': ['sum', 'mean']
        }).round(4)
        position_stats.columns = ['传中次数', '争顶次数', '争顶成功次数', '成功率']
        position_stats['成功率'] = position_stats['成功率'] * 100
        # 按传球方式统计
        style_stats = df.groupby('传球方式').agg({
            '是否接触': ['count', 'sum'],
            '争顶成功': ['sum', 'mean']
        }).round(4)
        style_stats.columns = ['传中次数', '争顶次数', '争顶成功次数', '成功率']
        style_stats['成功率'] = style_stats['成功率'] * 100
        return {
            'total': total_stats,
            'player': player_stats,
            'position': position_stats,
            'style': style_stats
        }
    def analyze_time_distribution(self):
        """分析比赛时间段的争顶成功率"""
        if self.df is None:
            return None
        df = self.df.copy()
        df['时间段'] = pd.cut(df['比赛时间'], 
                              bins=[0, 15, 30, 45, 60, 75, 95],
                              labels=['0-15', '15-30', '30-45', '45-60', '60-75', '75-90+'])
        time_stats = df.groupby('时间段').agg({
            '是否接触': ['count', 'sum'],
            '争顶成功': ['sum', 'mean']
        }).round(4)
        time_stats.columns = ['传中次数', '争顶次数', '争顶成功次数', '成功率']
        time_stats['成功率'] = time_stats['成功率'] * 100
        return time_stats
    def visualize_results(self, stats):
        """可视化统计结果"""
        fig, axes = plt.subplots(2, 2, figsize=(15, 12))
        # 1. 球员争顶成功率
        ax1 = axes[0, 0]
        player_data = stats['player'].head(10)
        ax1.barh(player_data.index, player_data['成功率'], color='steelblue')
        ax1.set_xlabel('成功率 (%)')
        ax1.set_title('球员争顶成功率 TOP10')
        ax1.set_xlim(0, 100)
        for i, v in enumerate(player_data['成功率']):
            ax1.text(v + 1, i, f'{v:.1f}%', va='center')
        # 2. 不同位置成功率
        ax2 = axes[0, 1]
        position_data = stats['position']
        colors = ['#ff9999', '#66b3ff', '#99ff99']
        ax2.bar(position_data.index, position_data['成功率'], color=colors)
        ax2.set_ylabel('成功率 (%)')
        ax2.set_title('不同位置的争顶成功率')
        ax2.set_ylim(0, 100)
        for i, v in enumerate(position_data['成功率']):
            ax2.text(i, v + 2, f'{v:.1f}%', ha='center')
        # 3. 传球方式成功率
        ax3 = axes[1, 0]
        style_data = stats['style']
        ax3.pie(style_data['争顶成功次数'], labels=style_data.index, 
                autopct='%1.1f%%', startangle=90)
        ax3.set_title('不同传球方式的争顶成功占比')
        # 4. 时间段趋势
        ax4 = axes[1, 1]
        time_stats = self.analyze_time_distribution()
        ax4.plot(time_stats.index, time_stats['成功率'], 
                marker='o', linewidth=2, markersize=8, color='crimson')
        ax4.set_xlabel('比赛时间段')
        ax4.set_ylabel('成功率 (%)')
        ax4.set_title('不同时间段的争顶成功率趋势')
        ax4.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.show()
    def generate_report(self):
        """生成统计报告"""
        stats = self.calculate_success_rate()
        print("="*60)
        print("高球传中争顶成功率分析报告")
        print("="*60)
        # 总体统计
        total = stats['total']
        print(f"\n【总体统计】")
        print(f"总传中次数:{total['总传中次数']}")
        print(f"争顶次数:{total['争顶次数']}")
        print(f"争顶成功次数:{total['争顶成功次数']}")
        print(f"总体成功率:{total['总体成功率']:.2f}%")
        # 球员统计
        print(f"\n【球员排名】")
        player_stats = stats['player']
        for player, row in player_stats.head(5).iterrows():
            print(f"{player}: {row['成功率']:.1f}% "
                  f"(成功{int(row['争顶成功次数'])}/{int(row['争顶次数'])}次)")
        # 位置统计
        print(f"\n【位置统计】")
        for position, row in stats['position'].iterrows():
            print(f"{position}: {row['成功率']:.1f}% "
                  f"({int(row['争顶成功次数'])}/{int(row['争顶次数'])}次)")
        # 传球方式
        print(f"\n【传球方式统计】")
        for style, row in stats['style'].iterrows():
            print(f"{style}: {row['成功率']:.1f}% "
                  f"({int(row['争顶成功次数'])}/{int(row['争顶次数'])}次)")
        return stats

使用示例

# 创建分析器实例
analyzer = HighBallStatAnalyzer()
# 生成示例数据
df = analyzer.generate_sample_data(200)
print("示例数据前5行:")
print(df.head())
# 计算统计结果
stats = analyzer.calculate_success_rate()
# 生成报告
analyzer.generate_report()
# 可视化结果
analyzer.visualize_results(stats)
# 分析时间段分布
time_stats = analyzer.analyze_time_distribution()
print("\n【时间段统计】")
print(time_stats)

额外功能:进阶分析

class AdvancedHighBallAnalyzer(HighBallStatAnalyzer):
    """高级高球争顶分析器"""
    def analyze_combination(self):
        """分析位置和传球方式的组合效果"""
        if self.df is None:
            return None
        combo_stats = self.df.groupby(['位置', '传球方式']).agg({
            '争顶成功': ['count', 'sum', 'mean']
        }).round(4)
        combo_stats.columns = ['总次数', '成功次数', '成功率']
        combo_stats['成功率'] = combo_stats['成功率'] * 100
        return combo_stats
    def find_optimal_strategy(self):
        """寻找最佳争顶策略"""
        combo = self.analyze_combination()
        best_combos = combo.nlargest(5, '成功率')
        print("\n【最佳争顶策略】")
        for idx, row in best_combos.iterrows():
            print(f"{idx[0]}-{idx[1]}: 成功率{row['成功率']:.1f}%")
        return best_combos
    def predict_success_rate(self, player_name, position, pass_style):
        """基于历史数据预测争顶成功率"""
        historical = self.df[
            (self.df['球员'] == player_name) & 
            (self.df['位置'] == position) & 
            (self.df['传球方式'] == pass_style)
        ]
        if len(historical) == 0:
            return None
        success_rate = historical['争顶成功'].mean() * 100
        sample_size = len(historical)
        return {
            '预测成功率': success_rate,
            '样本数': sample_size,
            '置信度': min(sample_size * 10, 100)  # 简单置信度评估
        }

运行示例

# 使用高级分析器
advanced_analyzer = AdvancedHighBallAnalyzer()
df = advanced_analyzer.generate_sample_data(500)
# 生成完整报告
stats = advanced_analyzer.generate_report()
# 寻找最佳策略
advanced_analyzer.find_optimal_strategy()
# 预测特定球员成功率
prediction = advanced_analyzer.predict_success_rate('张伟', '前锋', '角球传中')
print(f"\n【预测】张伟在角球传中的争顶成功率:{prediction['预测成功率']:.1f}%")
print(f"样本数量:{prediction['样本数']},置信度:{prediction['置信度']}%")

这个案例提供了:

  1. 基础统计:总体、球员、位置、传球方式的争顶成功率
  2. 时间分析:比赛不同时间段的争顶成功率变化
  3. 可视化展示:清晰的图表呈现统计数据
  4. 策略分析:找出最佳争顶组合策略
  5. 预测功能:根据历史数据预测特定场景的成功率

您可以根据实际需求调整数据源和分析维度。

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