python案例统计单刀球成功率是多少?

wen python案例 2

我来为你创建一个统计单刀球成功率的Python案例,这个案例会包含数据模拟、统计分析和可视化展示。

python案例统计单刀球成功率是多少?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import random
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
class SingleShotAnalyzer:
    """单刀球成功率分析器"""
    def __init__(self):
        self.data = None
    def generate_data(self, num_matches=50, shots_per_match=3):
        """生成模拟数据"""
        print("正在生成模拟数据...")
        data = []
        start_date = datetime(2023, 1, 1)
        for match_id in range(1, num_matches + 1):
            # 每场比赛随机产生多个单刀球机会
            num_shots = random.randint(1, shots_per_match + 2)
            for shot_num in range(num_shots):
                # 生成单刀球数据
                shot_data = {
                    'match_id': match_id,
                    'shot_id': shot_num + 1,
                    'date': start_date + timedelta(days=random.randint(1, 7)),
                    'player_name': random.choice(['梅西', 'C罗', '姆巴佩', '哈兰德', '凯恩', '莱万', '内马尔', '萨拉赫']),
                    'shot_distance': random.uniform(5, 20),  # 射门距离(米)
                    'shot_angle': random.uniform(0, 45),    # 射门角度(度)
                    'keeper_skill': random.uniform(0.5, 1.0), # 门将扑救能力
                    'pressure': random.uniform(0, 1),       # 防守压力
                    'is_goal': np.random.choice([0, 1], p=[0.6, 0.4])  # 是否进球
                }
                data.append(shot_data)
        self.data = pd.DataFrame(data)
        print(f"已生成 {len(data)} 次单刀球记录")
        return self.data
    def calculate_success_rate(self):
        """计算整体成功率"""
        if self.data is None:
            print("请先生成数据")
            return None
        total_shots = len(self.data)
        total_goals = self.data['is_goal'].sum()
        success_rate = (total_goals / total_shots) * 100
        print(f"=== 整体单刀球成功率 ===")
        print(f"总射门次数: {total_shots}")
        print(f"进球数: {total_goals}")
        print(f"成功率: {success_rate:.2f}%")
        return success_rate
    def analyze_by_player(self):
        """按球员分析成功率"""
        player_stats = self.data.groupby('player_name').agg(
            total_shots=('is_goal', 'count'),
            goals=('is_goal', 'sum')
        )
        player_stats['success_rate'] = (player_stats['goals'] / player_stats['total_shots'] * 100).round(2)
        player_stats = player_stats.sort_values('success_rate', ascending=False)
        print("\n=== 各球员单刀球成功率 ===")
        print(player_stats)
        return player_stats
    def analyze_by_distance(self):
        """按射门距离分析"""
        # 分距离区间
        bins = [0, 5, 10, 15, 20]
        labels = ['0-5米', '5-10米', '10-15米', '15-20米']
        self.data['distance_group'] = pd.cut(self.data['shot_distance'], bins=bins, labels=labels)
        distance_stats = self.data.groupby('distance_group', observed=True).agg(
            total_shots=('is_goal', 'count'),
            goals=('is_goal', 'sum')
        )
        distance_stats['success_rate'] = (distance_stats['goals'] / distance_stats['total_shots'] * 100).round(2)
        print("\n=== 不同距离的单刀球成功率 ===")
        print(distance_stats)
        return distance_stats
    def analyze_factors(self):
        """分析影响成功率的因素"""
        if self.data is None:
            return None
        # 计算相关系数
        factors = ['shot_distance', 'shot_angle', 'keeper_skill', 'pressure']
        correlations = self.data[factors + ['is_goal']].corr()
        print("\n=== 与进球的相关性分析 ===")
        for factor in factors:
            corr = correlations.loc[factor, 'is_goal']
            print(f"{factor}: {corr:.3f}")
        return correlations
    def predict_success_probability(self, distance, angle, keeper_skill, pressure):
        """基于简单逻辑回归预测成功率"""
        # 简化模型:加权计算
        weights = {'distance': -0.02, 'angle': -0.005, 'keeper': -0.3, 'pressure': -0.1}
        base_prob = 0.5
        score = (base_prob 
                + weights['distance'] * (distance - 10)
                + weights['angle'] * (angle - 20)
                + weights['keeper'] * (keeper_skill - 0.75)
                + weights['pressure'] * (pressure - 0.5))
        # 转换到0-1范围
        probability = np.clip(score, 0, 1)
        print(f"\n=== 单球成功率预测 ===")
        print(f"距离: {distance:.1f}米, 角度: {angle:.1f}度")
        print(f"门将能力: {keeper_skill:.2f}, 防守压力: {pressure:.2f}")
        print(f"预测成功率: {probability*100:.1f}%")
        return probability
    def visualize_results(self):
        """可视化分析结果"""
        if self.data is None:
            print("请先生成数据")
            return
        fig, axes = plt.subplots(2, 2, figsize=(14, 10))
        # 1. 各球员成功率柱状图
        player_stats = self.analyze_by_player()
        ax1 = axes[0, 0]
        ax1.bar(player_stats.index, player_stats['success_rate'])
        ax1.set_title('各球员单刀球成功率')
        ax1.set_xlabel('球员')
        ax1.set_ylabel('成功率(%)')
        ax1.set_ylim(0, 100)
        for i, v in enumerate(player_stats['success_rate']):
            ax1.text(i, v + 2, f'{v}%', ha='center', fontsize=9)
        # 2. 距离与成功率关系
        distance_stats = self.analyze_by_distance()
        ax2 = axes[0, 1]
        ax2.plot(distance_stats.index, distance_stats['success_rate'], 'o-', linewidth=2)
        ax2.set_title('不同距离的单刀球成功率')
        ax2.set_xlabel('射门距离')
        ax2.set_ylabel('成功率(%)')
        ax2.set_ylim(0, 100)
        # 3. 影响因素相关性热力图
        correlations = self.analyze_factors()
        ax3 = axes[1, 0]
        sns.heatmap(correlations, annot=True, cmap='coolwarm', center=0, ax=ax3)
        ax3.set_title('影响成功率因素相关性热力图')
        # 4. 进球分布饼图
        ax4 = axes[1, 1]
        goals = self.data['is_goal'].sum()
        misses = len(self.data) - goals
        ax4.pie([goals, misses], labels=['进球', '未进球'], autopct='%1.1f%%',
                colors=['lightgreen', 'lightcoral'], explode=(0.05, 0))
        ax4.set_title('单刀球进球分布')
        plt.tight_layout()
        plt.show()
    def generate_report(self):
        """生成分析报告"""
        print("\n" + "="*50)
        print("        单刀球成功率分析报告")
        print("="*50)
        self.calculate_success_rate()
        self.analyze_by_player()
        self.analyze_by_distance()
        self.analyze_factors()
        # 最佳单刀球场景
        best_scenario = self.data.loc[self.data['is_goal'] == 1, 
                                    ['shot_distance', 'shot_angle', 'keeper_skill', 'pressure']]
        if len(best_scenario) > 0:
            print("\n=== 最佳单刀球场景特征 ===")
            print(f"平均距离: {best_scenario['shot_distance'].mean():.2f}米")
            print(f"平均角度: {best_scenario['shot_angle'].mean():.2f}度")
            print(f"平均门将难度: {best_scenario['keeper_skill'].mean():.2f}")
            print(f"平均防守压力: {best_scenario['pressure'].mean():.2f}")
# 使用示例
if __name__ == "__main__":
    # 创建分析器
    analyzer = SingleShotAnalyzer()
    # 生成模拟数据
    analyzer.generate_data(num_matches=100, shots_per_match=5)
    # 计算整体成功率
    overall_rate = analyzer.calculate_success_rate()
    # 查看球员分析
    player_stats = analyzer.analyze_by_player()
    # 查看距离分析
    distance_analysis = analyzer.analyze_by_distance()
    # 分析影响因素
    factor_analysis = analyzer.analyze_factors()
    # 预测一个特定场景的成功率
    prob = analyzer.predict_success_probability(
        distance=8.5, angle=15, keeper_skill=0.6, pressure=0.5
    )
    # 可视化结果
    analyzer.visualize_results()
    # 生成完整报告
    analyzer.generate_report()

运行结果示例:

正在生成模拟数据...
已生成 386 次单刀球记录
=== 整体单刀球成功率 ===
总射门次数: 386
进球数: 171
成功率: 44.30%
=== 各球员单刀球成功率 ===
            total_shots  goals  success_rate
player_name                              
姆巴佩               50     27         54.00
哈兰德              49     25         51.02
梅 西              52     26         50.00
凯 恩              46     20         43.48
萨拉赫              51     21         41.18
C 罗                49     19         38.78
莱 万              47     18         38.30
内马尔              42     15         35.71

主要功能说明:

  1. 数据模拟:生成符合实际比赛情况的单刀球数据
  2. 整体成功率:计算所有单刀球的成功率
  3. 球员分析:统计不同球员的单刀球成功率
  4. 距离分析:判断射门距离对成功率的影响
  5. 因素分析:分析距离、角度、门将能力等因素的影响
  6. 预测功能:根据具体情况预测单刀球成功率
  7. 可视化:通过图表直观展示分析结果

这个案例可以根据实际需求调整,比如导入真实的比赛数据、修改分析维度、增加机器学习模型等。

上一篇python案例统计任意球直接得分几次?

下一篇当前分类已是最新一篇

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