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

wen python案例 2

本文目录导读:

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

  1. 示例数据(模拟)
  2. 判断是否为定位球
  3. 更通用的版本(支持自定义分类)
  4. 从 CSV / Excel 文件读取数据
  5. 可视化(饼图)
  6. 真实场景扩展建议

下面为你提供一个Python案例,用于统计定位球(如角球、任意球、点球等)在总进球中的得分占比

我们以足球比赛数据为例,假设有一份包含进球方式的数据集,计算“定位球进球数占总进球数的比例”。

示例数据(模拟)

# 模拟进球数据:每个元素是一个字典,包含进球的类型
goals = [
    {"player": "Messi", "type": "open_play"},
    {"player": "Ronaldo", "type": "free_kick"},   # 定位球(任意球)
    {"player": "Salah", "type": "penalty"},        # 定位球(点球)
    {"player": "Mbappe", "type": "open_play"},
    {"player": "Kane", "type": "corner"},          # 定位球(角球)
    {"player": "Lewandowski", "type": "open_play"},
    {"player": "Neymar", "type": "free_kick"},     # 定位球
    {"player": "Haaland", "type": "open_play"},
    {"player": "Benzema", "type": "penalty"},      # 定位球
    {"player": "De Bruyne", "type": "open_play"},
]

判断是否为定位球

定位球一般包括:

  • free_kick(任意球)
  • penalty(点球)
  • corner(角球)
  • throw_in(界外球,较少直接进球)
  • indirect_free_kick(间接任意球)

为简化,我们只统计上述前3种常见定位球。

# 定义定位球类型集合
set_piece_types = {"free_kick", "penalty", "corner"}
# 统计
total_goals = len(goals)
set_piece_goals = sum(1 for g in goals if g["type"] in set_piece_types)
# 计算占比
ratio = set_piece_goals / total_goals * 100
print(f"总进球数: {total_goals}")
print(f"定位球进球数: {set_piece_goals}")
print(f"定位球得分占比: {ratio:.2f}%")

输出结果:

总进球数: 10
定位球进球数: 5
定位球得分占比: 50.00%

更通用的版本(支持自定义分类)

from typing import List, Dict
def calculate_set_piece_ratio(goals: List[Dict], set_piece_types: set = {"free_kick", "penalty", "corner"}) -> float:
    """
    计算定位球进球占比
    :param goals: 进球数据列表,每个元素需包含 'type' 键
    :param set_piece_types: 定位球类型集合
    :return: 定位球占比(百分比)
    """
    total = len(goals)
    if total == 0:
        return 0.0
    set_piece_count = sum(1 for g in goals if g.get("type") in set_piece_types)
    return set_piece_count / total * 100
# 使用
ratio = calculate_set_piece_ratio(goals)
print(f"定位球得分占比: {ratio:.2f}%")

从 CSV / Excel 文件读取数据

如果你的数据在文件中(goals.csv):

player,type
Messi,open_play
Ronaldo,free_kick
Salah,penalty
...

可以使用 pandas:

import pandas as pd
df = pd.read_csv("goals.csv")
set_piece_types = {"free_kick", "penalty", "corner"}
total_goals = len(df)
set_piece_goals = df["type"].isin(set_piece_types).sum()
ratio = set_piece_goals / total_goals * 100
print(f"定位球得分占比: {ratio:.2f}%")

可视化(饼图)

import matplotlib.pyplot as plt
labels = ['定位球', '其他']
sizes = [set_piece_goals, total_goals - set_piece_goals]
colors = ['#ff9999', '#66b3ff']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)'定位球得分占比')
plt.axis('equal')
plt.show()

真实场景扩展建议

在实际应用(如足球分析平台)中,你可能需要:

  • 区分直接/间接定位球
  • 比赛、赛季、球队分组统计
  • 结合 xG(预期进球) 数据
  • 输出为报告或仪表盘

如果需要更具体的案例(如从某个比赛API获取数据、统计某支球队的定位球占比),请告诉我,我可以为你定制代码。

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