本文目录导读:

我来为您创建一个统计足球禁区内射门次数的Python案例,这个案例将模拟足球比赛数据并进行统计分析。
足球禁区射门统计系统
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import random
class FootballShootingAnalysis:
"""足球射门数据分析类"""
def __init__(self):
self.shooting_data = []
self.teams = ['皇家马德里', '巴塞罗那', '曼城', '利物浦', '拜仁慕尼黑']
self.players = {
'皇家马德里': ['本泽马', '维尼修斯', '罗德里戈', '莫德里奇', '克罗斯'],
'巴塞罗那': ['莱万', '登贝莱', '拉菲尼亚', '佩德里', '加维'],
'曼城': ['哈兰德', '福登', '德布劳内', '格拉利什', 'B席'],
'利物浦': ['萨拉赫', '努涅斯', '加克波', '迪亚斯', '若塔'],
'拜仁慕尼黑': ['凯恩', '穆西亚拉', '格纳布里', '萨内', '穆勒']
}
def generate_shooting_data(self, matches=100):
"""生成模拟射门数据"""
for match_id in range(1, matches + 1):
home_team = np.random.choice(self.teams)
away_team = np.random.choice([t for t in self.teams if t != home_team])
# 生成比赛射门数据
for team in [home_team, away_team]:
player_name = np.random.choice(self.players[team])
shots = np.random.randint(0, 15) # 每队0-15次射门
for shot in range(shots):
shooting = {
'比赛ID': match_id,
'日期': datetime.now().strftime('%Y-%m-%d'),
'球队': team,
'球员': player_name,
'射门区域': np.random.choice(['禁区内', '禁区外'], p=[0.65, 0.35]),
'射门类型': np.random.choice(['左脚', '右脚', '头球', '其他'], p=[0.35, 0.40, 0.20, 0.05]),
'是否射正': np.random.choice([True, False], p=[0.45, 0.55]),
'是否进球': np.random.choice([True, False], p=[0.12, 0.88]),
'射门时间': np.random.randint(1, 91), # 比赛时间1-90分钟
'射门距离': np.round(np.random.uniform(5, 30), 1) # 射门距离5-30米
}
self.shooting_data.append(shooting)
return pd.DataFrame(self.shooting_data)
def analyze_penalty_area_shots(self, df):
"""分析禁区内射门数据"""
print("=" * 60)
print("足球禁区射门统计分析")
print("=" * 60)
# 1. 基础统计
total_shots = len(df)
penalty_area_shots = df[df['射门区域'] == '禁区内']
outside_shots = df[df['射门区域'] == '禁区外']
print(f"\n1. 总体射门数据:")
print(f" 总射门次数: {total_shots}")
print(f" 禁区内射门: {len(penalty_area_shots)} ({len(penalty_area_shots)/total_shots*100:.1f}%)")
print(f" 禁区外射门: {len(outside_shots)} ({len(outside_shots)/total_shots*100:.1f}%)")
# 2. 各球队禁区射门统计
print(f"\n2. 各球队禁区射门统计:")
team_shots = df.groupby('球队').agg({
'射门区域': lambda x: (x == '禁区内').sum(),
'是否进球': 'sum'
}).rename(columns={'射门区域': '禁区射门数', '是否进球': '进球数'})
team_shots['禁区射门占比'] = (team_shots['禁区射门数'] /
df.groupby('球队')['射门区域'].count() * 100).round(1)
print(team_shots)
# 3. 球员禁区射门数据
print(f"\n3. 球员禁区射门TOP10:")
player_shots = df[df['射门区域'] == '禁区内'].groupby('球员').agg({
'射门次数': 'count',
'是否进球': 'sum'
}).nlargest(10, '射门次数')
player_shots['射门转化率'] = (player_shots['是否进球'] / player_shots['射门次数'] * 100).round(1)
print(player_shots)
# 4. 禁区与禁区外射门效果对比
print(f"\n4. 射门区域效果对比:")
comparison = df.groupby('射门区域').agg({
'射门次数': 'count',
'是否进球': 'sum',
'是否射正': 'sum'
})
comparison['进球率'] = (comparison['是否进球'] / comparison['射门次数'] * 100).round(2)
comparison['射正率'] = (comparison['是否射正'] / comparison['射门次数'] * 100).round(2)
print(comparison)
return {
'total_shots': total_shots,
'penalty_area_shots': len(penalty_area_shots),
'outside_shots': len(outside_shots)
}
def visualize_analysis(self, df):
"""可视化分析结果"""
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
# 1. 射门区域分布饼图
ax1 = axes[0, 0]
penalty_ratio = df['射门区域'].value_counts()
colors = ['#FF6B6B', '#4ECDC4']
ax1.pie(penalty_ratio.values, labels=penalty_ratio.index, autopct='%1.1f%%',
colors=colors, startangle=90)
ax1.set_title('射门区域分布')
# 2. 各队禁区射门柱状图
ax2 = axes[0, 1]
team_data = df[df['射门区域'] == '禁区内'].groupby('球队').size()
team_data.sort_values(ascending=False).plot(kind='bar', ax=ax2, color='#95a5a6')
ax2.set_title('各队禁区内射门次数')
ax2.set_ylabel('射门次数')
ax2.tick_params(axis='x', rotation=45)
# 3. 射门时间分布(禁区vs禁区外)
ax3 = axes[1, 0]
penalty_time = df[df['射门区域'] == '禁区内']['射门时间'].value_counts()
outside_time = df[df['射门区域'] == '禁区外']['射门时间'].value_counts()
ax3.hist([penalty_time.index, outside_time.index],
bins=[i for i in range(0, 95, 10)],
label=['禁区内', '禁区外'],
alpha=0.7, color=['#e74c3c', '#3498db'])
ax3.set_title('射门时间分布')
ax3.set_xlabel('比赛时间(分钟)')
ax3.set_ylabel('射门次数')
ax3.legend()
# 4. 射门距离分布
ax4 = axes[1, 1]
penalty_distance = df[df['射门区域'] == '禁区内']['射门距离']
outside_distance = df[df['射门区域'] == '禁区外']['射门距离']
ax4.boxplot([penalty_distance, outside_distance],
labels=['禁区内', '禁区外'])
ax4.set_title('射门距离分布')
ax4.set_ylabel('射门距离(米)')
plt.tight_layout()
plt.show()
def shooting_heatmap(self, df):
"""创建射门热力图"""
fig, ax = plt.subplots(figsize=(12, 8))
# 模拟球场坐标
x = np.random.uniform(-50, 50, len(df))
y = np.random.uniform(-35, 35, len(df))
# 禁区内射门用红色,禁区外用蓝色
colors = ['red' if i == '禁区内' else 'blue' for i in df['射门区域']]
ax.scatter(x, y, c=colors, alpha=0.6, s=30)
# 画禁区框
ax.plot([-16.5, 16.5, 16.5, -16.5, -16.5],
[-35, -35, -12, -12, -35], 'k-', linewidth=2)
# 画球门
ax.plot([-7.32, 7.32], [-35, -35], 'g-', linewidth=3)
ax.set_xlim(-50, 50)
ax.set_ylim(-35, 35)
ax.set_title('射门分布图(红色=禁区内,蓝色=禁区外)')
ax.set_xlabel('球场宽度(米)')
ax.set_ylabel('球场长度(米)')
ax.grid(True, alpha=0.2)
# 添加图例
from matplotlib.patches import Patch
legend_elements = [Patch(facecolor='red', alpha=0.7, label='禁区内射门'),
Patch(facecolor='blue', alpha=0.7, label='禁区外射门')]
ax.legend(handles=legend_elements, loc='upper right')
plt.gca().invert_yaxis() # 使球场方向正确
plt.show()
# 主程序
def main():
# 创建分析对象
analysis = FootballShootingAnalysis()
# 生成模拟数据(100场比赛)
print("正在生成模拟数据...")
df = analysis.generate_shooting_data(matches=100)
# 输出数据概览
print("\n数据预览:")
print(df.head(10))
print(f"\n总射门数据量: {len(df)}")
# 统计分析
stats = analysis.analyze_penalty_area_shots(df)
# 可视化展示
analysis.visualize_analysis(df)
# 创建射门热力图
analysis.shooting_heatmap(df)
# 额外分析比较
print("\n5. 禁区内外射门效果对比总结:")
penalty_rate = (stats['penalty_area_shots'] / stats['total_shots'] * 100)
outside_rate = (stats['outside_shots'] / stats['total_shots'] * 100)
print(f" 禁区内射门占比: {penalty_rate:.1f}%")
print(f" 禁区外射门占比: {outside_rate:.1f}%")
# 计算射门效率
penalty_goals = df[(df['射门区域'] == '禁区内') & (df['是否进球'] == True)].shape[0]
outside_goals = df[(df['射门区域'] == '禁区外') & (df['是否进球'] == True)].shape[0]
print(f" 禁区内进球: {penalty_goals} 个")
print(f" 禁区外进球: {outside_goals} 个")
print(f" 禁区内进球转化率: {(penalty_goals/stats['penalty_area_shots']*100):.1f}%")
print(f" 禁区外进球转化率: {(outside_goals/stats['outside_shots']*100):.1f}%")
return df
if __name__ == "__main__":
# 运行主程序
df = main()
# 导出数据
df.to_csv('football_shooting_analysis.csv', index=False)
print("\n数据已保存至 football_shooting_analysis.csv")
核心功能说明
数据生成
- 自动生成模拟的足球比赛射门数据
- 包含比赛ID、球队、球员、射门区域、射门类型等字段
统计功能
- 总体射门数据分析
- 各球队禁区内射门次数统计
- 球员禁区射门TOP排名
- 禁区内外进球转化率对比
可视化展示
- 射门区域分布饼图
- 各队禁区内射门柱状图
- 射门时间分布直方图
- 射门距离箱线图
- 球场射门热力图
实用功能
- 数据导出为CSV文件
- 自动化数据分析
- 可配置球队和球员
这个程序可以帮助教练和分析师快速了解球队的禁区射门情况,优化战术选择,您可以根据实际需要修改球队名称、球员名单等参数。