我来为您创建一个足球门前抢点射门统计分析的Python案例,这个案例将模拟统计两名前锋在门前抢点射门的数据。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta
import random
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用于显示中文
plt.rcParams['axes.unicode_minus'] = False # 用于显示负号
# 生成模拟数据
def generate_match_data():
"""生成一场比赛的模拟射门数据"""
players = ['前锋A', '前锋B']
match_data = []
# 模拟比赛时间(90分钟)
for minute in range(1, 91):
# 模拟前锋A的射门
if random.random() < 0.15: # 15%概率产生射门
match_data.append({
'球员': '前锋A',
'时间': minute,
'射门类型': random.choice(['抢点射门', '远射', '头球']),
'位置': random.choice(['小禁区', '点球点', '大禁区']),
'射门结果': random.choice(['进球', '射正', '射偏', '被扑出'])
})
# 模拟前锋B的射门
if random.random() < 0.12: # 12%概率产生射门
match_data.append({
'球员': '前锋B',
'时间': minute,
'射门类型': random.choice(['抢点射门', '远射', '头球']),
'位置': random.choice(['小禁区', '点球点', '大禁区']),
'射门结果': random.choice(['进球', '射正', '射偏', '被扑出'])
})
return pd.DataFrame(match_data)
# 生成5场比赛的数据
def generate_season_data(num_matches=5):
"""生成多场比赛数据"""
all_data = []
for match_num in range(1, num_matches + 1):
match_df = generate_match_data()
match_df['比赛'] = f'第{match_num}轮'
all_data.append(match_df)
return pd.concat(all_data, ignore_index=True)
# 主分析函数
def analyze_goal_area_shots(data):
"""分析门前抢点射门对比"""
# 筛选抢点射门数据
goal_area_shots = data[data['射门类型'] == '抢点射门'].copy()
# 基础统计
print("=" * 60)
print("门前抢点射门统计对比")
print("=" * 60)
# 1. 总体射门次数对比
shots_by_player = data.groupby('球员').size().reset_index(name='总射门次数')
goal_area_by_player = goal_area_shots.groupby('球员').size().reset_index(name='抢点射门次数')
goal_rate_by_player = goal_area_shots[goal_area_shots['射门结果'] == '进球'].groupby('球员').size().reset_index(name='进球数')
# 合并数据
summary = shots_by_player.merge(goal_area_by_player, on='球员', how='left')
summary = summary.merge(goal_rate_by_player, on='球员', how='left')
summary = summary.fillna(0)
summary['抢点射门占比'] = (summary['抢点射门次数'] / summary['总射门次数'] * 100).round(1)
summary['抢点射门转化率'] = (summary['进球数'] / summary['抢点射门次数'] * 100).round(1)
print("\n📊 球员射门统计总览:")
print("-" * 60)
print(summary.to_string(index=False))
# 2. 按比赛轮次对比
weekly_data = goal_area_shots.groupby(['球员', '比赛']).size().unstack(fill_value=0)
print("\n📈 各场比赛抢点射门次数:")
print("-" * 60)
print(weekly_data)
return goal_area_shots, summary, weekly_data
# 可视化函数
def visualize_comparison(goal_area_shots, summary, weekly_data):
"""创建数据可视化图表"""
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
fig.suptitle('门前抢点射门分析', fontsize=16, fontweight='bold')
# 1. 抢点射门次数对比柱状图
ax1 = axes[0, 0]
players = summary['球员']
values = summary['抢点射门次数']
bars = ax1.bar(players, values, color=['#FF6B6B', '#4ECDC4'], width=0.5)
ax1.set_title('抢点射门总次数对比', fontsize=12)
ax1.set_ylabel('射门次数')
for bar, val in zip(bars, values):
ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
str(int(val)), ha='center', va='bottom')
# 2. 抢点射门占比饼图
ax2 = axes[0, 1]
goal_rate = summary['抢点射门占比']
ax2.pie(goal_rate, labels=players, autopct='%1.1f%%',
colors=['#FF6B6B', '#4ECDC4'], startangle=90)
ax2.set_title('抢点射门占比对比', fontsize=12)
# 3. 各场比赛抢点射门趋势
ax3 = axes[1, 0]
x = np.arange(len(weekly_data.columns))
width = 0.3
if '前锋A' in weekly_data.index:
ax3.bar(x - width/2, weekly_data.loc['前锋A'], width, label='前锋A', color='#FF6B6B')
if '前锋B' in weekly_data.index:
ax3.bar(x + width/2, weekly_data.loc['前锋B'], width, label='前锋B', color='#4ECDC4')
ax3.set_xlabel('比赛场次')
ax3.set_ylabel('射门次数')
ax3.set_title('各场比赛抢点射门对比', fontsize=12)
ax3.set_xticks(x)
ax3.set_xticklabels(weekly_data.columns, rotation=45)
ax3.legend()
# 4. 射门位置分布
ax4 = axes[1, 1]
if not goal_area_shots.empty:
position_dist = goal_area_shots.groupby(['球员', '位置']).size().unstack(fill_value=0)
position_dist.plot(kind='bar', ax=ax4, color=['#FFA07A', '#98D8C8', '#FF69B4'])
ax4.set_title('抢点射门位置分布', fontsize=12)
ax4.set_xlabel('球员')
ax4.set_ylabel('射门次数')
ax4.legend(title='射门位置')
ax4.tick_params(axis='x', rotation=0)
plt.tight_layout()
return fig
# 详细分析函数
def detailed_analysis(goal_area_shots, summary):
"""详细分析抢点射门表现"""
print("\n" + "=" * 60)
print("🔍 详细分析")
print("=" * 60)
# 射门结果分布
shots_result_dist = goal_area_shots.groupby(['球员', '射门结果']).size().unstack(fill_value=0)
print("\n📊 抢点射门结果分布:")
print("-" * 60)
print(shots_result_dist)
# 进球效率分析
print("\n⚽ 抢点射门效率分析:")
print("-" * 60)
for player in summary['球员']:
player_data = goal_area_shots[goal_area_shots['球员'] == player]
if not player_data.empty:
player_info = {
'球员': player,
'总射门': len(player_data),
'进球': (player_data['射门结果'] == '进球').sum(),
'射正率': ((player_data['射门结果'].isin(['进球', '射正'])).sum() / len(player_data) * 100).round(1),
'每场平均': (len(player_data) / len(player_data['比赛'].unique())).round(1),
'最佳射门区域': player_data['位置'].mode().values[0]
}
print(f" {player}: 总共{player_info['总射门']}次抢点射门, "
f"进球{player_info['进球']}个, "
f"射正率{player_info['射正率']}%, "
f"场均{player_info['每场平均']}次, "
f"最佳区域: {player_info['最佳射门区域']}")
# 比赛关键时刻分析(最后15分钟)
last_15_subs = goal_area_shots[goal_area_shots['时间'] >= 75]
last_15_subs_group = last_15_subs.groupby('球员').size()
print("\n⏰ 比赛最后15分钟抢点射门统计:")
print("-" * 60)
if not last_15_subs_group.empty:
for player in summary['球员']:
count = last_15_subs_group.get(player, 0)
print(f" {player}: {count}次")
# 生成分析建议
print("\n💡 分析建议:")
print("-" * 60)
# 找出抢点射门更积极的前锋
goal_area_total = summary.set_index('球员')['抢点射门次数']
best_player = goal_area_total.idxmax()
if goal_area_total['前锋A'] > goal_area_total['前锋B']:
print(f" 前锋A更倾向于门前抢点射门,可以保持这种进攻方式")
print(f" 但同时要注意前锋B的使用,可以考虑增加其门前射门机会")
else:
print(f" 前锋B更倾向于门前抢点射门,可以保持这种进攻方式")
print(f" 但同时要注意前锋A的使用,可以考虑增加其门前射门机会")
# 主程序执行
def main():
"""主程序入口"""
# 生成数据
print("⏳ 正在生成比赛数据...")
match_data = generate_season_data(num_matches=5)
print(f"✓ 数据生成完成,共{len(match_data)}次射门记录\n")
# 执行分析
goal_area_shots, summary, weekly_data = analyze_goal_area_shots(match_data)
# 详细分析
detailed_analysis(goal_area_shots, summary)
# 可视化
fig = visualize_comparison(goal_area_shots, summary, weekly_data)
# 保存结果
output_filename = 'goal_area_shot_analysis.png'
fig.savefig(output_filename, dpi=300, bbox_inches='tight')
print(f"\n✅ 图表已保存为: {output_filename}")
# 导出详细数据
excel_filename = 'goal_area_shot_analysis.xlsx'
with pd.ExcelWriter(excel_filename, engine='openpyxl') as writer:
summary.to_excel(writer, sheet_name='总览', index=False)
weekly_data.to_excel(writer, sheet_name='每周数据')
goal_area_shots.to_excel(writer, sheet_name='抢点射门明细', index=False)
print(f"✅ 详细数据已导出为: {excel_filename}")
# 显示图表
plt.show()
if __name__ == "__main__":
main()
这个程序还包含一个更简洁的分析版本:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# 简化版本的抢点射门统计
def simple_comparison():
"""简单版本的门前抢点射门对比"""
# 模拟两场比赛数据
data = {
'球员': ['前锋A', '前锋A', '前锋A', '前锋A', '前锋B', '前锋B', '前锋B'],
'比赛': ['第一场', '第一场', '第二场', '第二场', '第一场', '第一场', '第二场'],
'射门类型': ['抢点', '抢点', '抢点', '抢点', '抢点', '远射', '抢点'],
'时间': [23, 45, 67, 78, 12, 56, 88]
}
df = pd.DataFrame(data)
# 筛选抢点射门
goal_shots = df[df['射门类型'] == '抢点']
# 分组统计
comparison = goal_shots.groupby(['球员', '比赛']).size().unstack(fill_value=0)
comparison['总计'] = comparison.sum(axis=1)
print("门前抢点射门次数对比:")
print(comparison)
# 可视化
comparison[['总计']].plot(kind='bar', figsize=(8, 5))
plt.title('球员抢点射门总次数对比')
plt.ylabel('射门次数')
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
return comparison
# 运行简化版本
simple_comparison()
主要功能:
- 数据模拟:生成多场比赛的射门数据
- 统计分析:对比两名前锋的抢点射门次数、进球效率
- 可视化展示:柱状图、饼图、趋势图等多种图表
- 详细报告:输出清晰的统计报告和分析建议
输出包括:
- 抢点射门次数统计
- 进球转化率对比
- 各场比赛表现趋势
- 射门位置分布
- 关键时刻(比赛末段)表现
- 自动生成分析建议和图表
运行后会自动生成分析图表和Excel报表,方便进一步分析。