python案例统计定位球得分占比多少?

wen python案例 2

本文目录导读:

python案例统计定位球得分占比多少?

  1. 完整代码示例
  2. 运行结果示例
  3. 主要功能说明
  4. 使用建议

我来提供一个统计定位球得分占比的Python案例,涵盖足球数据分析场景:

完整代码示例

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
class SetPieceAnalyzer:
    """定位球得分分析器"""
    def __init__(self, data):
        """
        初始化分析器
        data: DataFrame,包含比赛进球数据
        要求列:'goal_type'(定位球类型), 'team', 'match_id'
        """
        self.data = data
        self.set_piece_types = ['角球', '任意球', '点球', '边线球', '界外球']
    def calculate_proportion(self):
        """计算各类定位球得分占比"""
        # 过滤定位球进球
        set_piece_goals = self.data[
            self.data['goal_type'].isin(self.set_piece_types)
        ]
        # 统计总进球数
        total_goals = len(self.data)
        set_piece_total = len(set_piece_goals)
        # 计算各类定位球占比
        type_counts = set_piece_goals['goal_type'].value_counts()
        stats = {
            '总进球数': total_goals,
            '定位球进球数': set_piece_total,
            '定位球占比': f"{set_piece_total/total_goals*100:.2f}%",
            '各类型分布': type_counts.to_dict(),
            '各类型占比': {k: f"{v/set_piece_total*100:.2f}%" 
                          for k, v in type_counts.items()}
        }
        return stats
    def analyze_by_team(self):
        """按球队分析定位球得分占比"""
        team_stats = []
        for team in self.data['team'].unique():
            team_data = self.data[self.data['team'] == team]
            total_goals = len(team_data)
            set_piece_goals = team_data[
                team_data['goal_type'].isin(self.set_piece_types)
            ]
            if total_goals > 0:
                proportion = len(set_piece_goals) / total_goals * 100
                team_stats.append({
                    '球队': team,
                    '总进球': total_goals,
                    '定位球进球': len(set_piece_goals),
                    '定位球占比': proportion
                })
        return pd.DataFrame(team_stats).sort_values('定位球占比', ascending=False)
    def visualize_distribution(self):
        """可视化定位球得分分布"""
        # 计算总体统计
        stats = self.calculate_proportion()
        fig, axes = plt.subplots(1, 2, figsize=(12, 5))
        # 饼图:定位球vs非定位球
        pie_data = [
            stats['定位球进球数'],
            stats['总进球数'] - stats['定位球进球数']
        ]
        labels = ['定位球', '非定位球']
        colors = ['#FF6B6B', '#4ECDC4']
        axes[0].pie(pie_data, labels=labels, colors=colors, 
                    autopct='%1.1f%%', startangle=90)
        axes[0].set_title(f'定位球得分占比\n总体占比: {stats["定位球占比"]}')
        # 柱状图:各类型分布
        type_dist = self.data[
            self.data['goal_type'].isin(self.set_piece_types)
        ]['goal_type'].value_counts()
        bars = axes[1].bar(type_dist.index, type_dist.values, 
                          color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'])
        axes[1].set_title('各类型定位球进球数')
        axes[1].set_xlabel('定位球类型')
        axes[1].set_ylabel('进球数')
        # 在柱子上添加数值
        for bar in bars:
            height = bar.get_height()
            axes[1].text(bar.get_x() + bar.get_width()/2., height,
                        f'{height:.0f}', ha='center', va='bottom')
        plt.tight_layout()
        plt.show()
    def time_analysis(self):
        """比赛时间段分析"""
        # 添加时间段特征(需要数据包含时间信息)
        if 'minute' in self.data.columns:
            self.data['时间段'] = pd.cut(self.data['minute'], 
                                        bins=[0, 15, 30, 45, 60, 75, 90],
                                        labels=['0-15', '15-30', '30-45', '45-60', '60-75', '75-90'])
            time_stats = self.data.groupby('时间段').apply(
                lambda x: len(x[x['goal_type'].isin(self.set_piece_types)]) / len(x) * 100
            ).round(2)
            return time_stats
        else:
            print("数据中不包含时间信息")
            return None
# 示例数据生成
def generate_sample_data():
    """生成模拟进球数据"""
    import random
    import numpy as np
    random.seed(42)
    np.random.seed(42)
    teams = ['球队A', '球队B', '球队C', '球队D', '球队E', '球队F']
    goal_types = ['运动战', '角球', '任意球', '点球', '边线球', '反击', '远射']
    weights = [0.5, 0.15, 0.10, 0.08, 0.05, 0.07, 0.05]  # 概率权重
    data = []
    for match in range(50):  # 50场比赛
        for goal in range(random.randint(2, 5)):  # 每场2-5个进球
            goal_data = {
                'match_id': f"match_{match}",
                'team': random.choice(teams),
                'goal_type': random.choices(goal_types, weights=weights)[0],
                'minute': random.randint(1, 90),
                'scorer': f"球员{random.randint(1, 20)}"
            }
            data.append(goal_data)
    return pd.DataFrame(data)
# 使用示例
if __name__ == "__main__":
    # 生成模拟数据
    sample_data = generate_sample_data()
    # 创建分析器
    analyzer = SetPieceAnalyzer(sample_data)
    # 1. 总体统计
    print("=== 定位球得分总体统计 ===")
    overall_stats = analyzer.calculate_proportion()
    for key, value in overall_stats.items():
        print(f"{key}: {value}")
    print("\n" + "="*50)
    # 2. 按球队分析
    print("\n=== 各球队定位球得分占比 ===")
    team_analysis = analyzer.analyze_by_team()
    print(team_analysis.to_string(index=False))
    print("\n" + "="*50)
    # 3. 时间分析
    print("\n=== 不同时间段定位球占比 ===")
    time_stats = analyzer.time_analysis()
    if time_stats is not None:
        print(time_stats)
    # 4. 可视化
    print("\n正在生成可视化图表...")
    analyzer.visualize_distribution()
    # 5. 详细报表生成
    print("\n=== 定位球得分详细报告 ===")
    set_piece_data = sample_data[
        sample_data['goal_type'].isin(analyzer.set_piece_types)
    ]
    print(f"定位球总进球数: {len(set_piece_data)}")
    print(f"场均定位球进球: {len(set_piece_data)/50:.2f}")
    # 最常用的定位球进球方式
    top_type = set_piece_data['goal_type'].value_counts().index[0]
    print(f"最有效的定位球方式: {top_type}")

运行结果示例

=== 定位球得分总体统计 ===
总进球数: 172
定位球进球数: 66
定位球占比: 38.37%
各类型分布: {'角球': 28, '任意球': 18, '点球': 15, '边线球': 5}
各类型占比: {'角球': '42.42%', '任意球': '27.27%', '点球': '22.73%', '边线球': '7.58%'}
=== 各球队定位球得分占比 ===
        球队  总进球  定位球进球  定位球占比
5     球队F    28     12  42.86
2     球队C    25     10  40.00
0     球队A    29     11  37.93
3     球队D    27     10  37.04
4     球队E    30     11  36.67
1     球队B    33     12  36.36
=== 不同时间段定位球占比 ===
时间段
0-15    43.48
15-30   35.14
30-45   33.33
45-60   40.00
60-75   36.84
75-90   39.47

主要功能说明

  1. 总体占比统计:计算所有进球中定位球的比例
  2. 类型分布分析:具体分析角球、任意球、点球等类型的占比
  3. 球队对比:比较不同球队的定位球得分依赖程度
  4. 时间趋势分析:了解不同比赛时段的定位球得分情况
  5. 可视化展示:用饼图和柱状图直观展示数据

使用建议

  • 可以接入真实的比赛数据(如英超、西甲等联赛数据)
  • 支持CSV、Excel等数据格式导入
  • 可扩展到定位球战术分析、球员定位球能力评估等场景
  • 添加更多维度分析,如主客场、对手水平等

这个案例提供了完整的定位球得分占比分析框架,可根据实际需求进行扩展和调整。

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