本文目录导读:

我来给你一个分析足球队近期状态的Python案例,这个案例会从多个维度评估球队状态,包括胜率、进球效率、防守表现等。
完整代码实现
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import seaborn as sns
class TeamFormAnalyzer:
def __init__(self):
"""初始化球队状态分析器"""
# 模拟球队近期比赛数据
self.teams_data = self._generate_teams_data()
def _generate_teams_data(self):
"""生成模拟的球队比赛数据"""
teams = ['曼城', '利物浦', '阿森纳', '切尔西', '曼联']
data = []
for team in teams:
# 生成最近10场比赛的数据
for i in range(10):
match_date = datetime.now() - timedelta(days=i*3)
data.append({
'team': team,
'date': match_date,
'goals_scored': np.random.randint(0, 4),
'goals_conceded': np.random.randint(0, 3),
'possession': np.random.randint(40, 70),
'shots': np.random.randint(8, 20),
'shots_on_target': np.random.randint(3, 10),
'home': np.random.choice([True, False])
})
return pd.DataFrame(data)
def calculate_form_metrics(self, team):
"""计算球队状态指标"""
team_data = self.teams_data[self.teams_data['team'] == team].copy()
team_data['date'] = pd.to_datetime(team_data['date'])
team_data = team_data.sort_values('date', ascending=False).head(6)
# 计算结果
wins = (team_data['goals_scored'] > team_data['goals_conceded']).sum()
draws = (team_data['goals_scored'] == team_data['goals_conceded']).sum()
losses = (team_data['goals_scored'] < team_data['goals_conceded']).sum()
# 场均进球和失球
avg_goals_for = team_data['goals_scored'].mean()
avg_goals_against = team_data['goals_conceded'].mean()
# 射门效率
shot_efficiency = (team_data['shots_on_target'].sum() / team_data['shots'].sum()) * 100
# 控球率
avg_possession = team_data['possession'].mean()
# 计算状态分数 (0-100)
form_score = self._calculate_form_score(team_data)
return {
'team': team,
'wins': wins,
'draws': draws,
'losses': losses,
'win_rate': wins / len(team_data) * 100,
'avg_goals_for': round(avg_goals_for, 2),
'avg_goals_against': round(avg_goals_against, 2),
'shot_efficiency': round(shot_efficiency, 2),
'avg_possession': round(avg_possession, 2),
'form_score': form_score,
'recent_results': team_data['result'].tolist() if 'result' in team_data.columns else self._get_result_strings(team_data)
}
def _get_result_strings(self, team_data):
"""获取比赛结果字符串"""
results = []
for _, row in team_data.iterrows():
if row['goals_scored'] > row['goals_conceded']:
results.append('W') # Win
elif row['goals_scored'] == row['goals_conceded']:
results.append('D') # Draw
else:
results.append('L') # Loss
return results
def _calculate_form_score(self, team_data):
"""计算球队状态综合评分"""
score = 0
# 根据最近5场比赛结果计分
recent_games = team_data.head(5)
for i, (_, row) in enumerate(recent_games.iterrows()):
# 最近的比赛权重更高
weight = 1.0 / (i + 1)
if row['goals_scored'] > row['goals_conceded']:
score += 30 * weight # 胜
elif row['goals_scored'] == row['goals_conceded']:
score += 15 * weight # 平
# 负不计分
# 进球效率加分
if team_data['goals_scored'].mean() >= 2:
score += 15
elif team_data['goals_scored'].mean() >= 1.5:
score += 10
# 防守表现加分
if team_data['goals_conceded'].mean() <= 1:
score += 15
elif team_data['goals_conceded'].mean() <= 1.5:
score += 8
# 控球率加分
if team_data['possession'].mean() >= 55:
score += 10
return min(score, 100) # 最高100分
def analyze_all_teams(self):
"""分析所有球队状态"""
results = []
for team in self.teams_data['team'].unique():
metrics = self.calculate_form_metrics(team)
results.append(metrics)
df = pd.DataFrame(results)
df = df.sort_values('form_score', ascending=False)
return df
def get_team_prediction(self, team, opponent=None):
"""获取球队状态预测"""
metrics = self.calculate_form_metrics(team)
prediction = f"📊 {team} 近期状态分析:\n"
prediction += f"🏆 状态评分:{metrics['form_score']}/100\n"
prediction += f"📈 胜率:{metrics['win_rate']:.1f}%\n"
prediction += f"⚽ 场均进球:{metrics['avg_goals_for']}\n"
prediction += f"🛡️ 场均失球:{metrics['avg_goals_against']}\n"
prediction += f"🎯 射门效率:{metrics['shot_efficiency']}%\n"
prediction += f"🔑 场均控球率:{metrics['avg_possession']}%\n"
# 状态评级
if metrics['form_score'] >= 80:
prediction += f"🔥 状态:非常火热,处于巅峰状态!"
elif metrics['form_score'] >= 60:
prediction += f"✅ 状态:良好,发挥稳定!"
elif metrics['form_score'] >= 40:
prediction += f"⚠️ 状态:一般,有提升空间!"
else:
prediction += f"⚠️ 状态:低迷,需要调整!"
return prediction
def visualize_team_form(self, team):
"""可视化球队近期表现"""
team_data = self.teams_data[self.teams_data['team'] == team].copy()
team_data['date'] = pd.to_datetime(team_data['date'])
team_data = team_data.sort_values('date')
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# 1. 进球和失球趋势
ax1 = axes[0, 0]
ax1.plot(team_data.index, team_data['goals_scored'], 'o-', label='进球', color='green')
ax1.plot(team_data.index, team_data['goals_conceded'], 'o-', label='失球', color='red')
ax1.set_title(f'{team} - 进球失球趋势')
ax1.set_xlabel('比赛场次')
ax1.set_ylabel('球数')
ax1.legend()
ax1.grid(True, alpha=0.3)
# 2. 控球率变化
ax2 = axes[0, 1]
ax2.plot(team_data.index, team_data['possession'], 'o-', color='blue')
ax2.set_title(f'{team} - 控球率变化')
ax2.set_xlabel('比赛场次')
ax2.set_ylabel('控球比例(%)')
ax2.grid(True, alpha=0.3)
# 3. 射门效率
ax3 = axes[1, 0]
efficiency = team_data['shots_on_target'] / team_data['shots'] * 100
ax3.bar(team_data.index, efficiency, color='purple', alpha=0.7)
ax3.set_title(f'{team} - 射门效率')
ax3.set_xlabel('比赛场次')
ax3.set_ylabel('射门效率(%)')
ax3.grid(True, alpha=0.3)
# 4. 胜负分布
ax4 = axes[1, 1]
results = []
for _, row in team_data.iterrows():
if row['goals_scored'] > row['goals_conceded']:
results.append('胜')
elif row['goals_scored'] == row['goals_conceded']:
results.append('平')
else:
results.append('负')
result_counts = pd.Series(results).value_counts()
colors = {'胜': 'green', '平': 'yellow', '负': 'red'}
ax4.pie(result_counts.values, labels=result_counts.index,
colors=[colors.get(x) for x in result_counts.index],
autopct='%1.1f%%')
ax4.set_title(f'{team} - 近期战绩分布')
plt.tight_layout()
plt.show()
# 主程序
def main():
# 创建分析器实例
analyzer = TeamFormAnalyzer()
# 1. 查看所有球队状态排名
print("=" * 60)
print("🏆 球队状态排名")
print("=" * 60)
all_teams_df = analyzer.analyze_all_teams()
print(all_teams_df[['team', 'form_score', 'win_rate', 'avg_goals_for', 'avg_goals_against']].to_string(index=False))
# 2. 查看特定球队的详细状态
print("\n" + "=" * 60)
print("📊 详细球队分析")
print("=" * 60)
for team in ['曼城', '利物浦', '阿森纳']:
prediction = analyzer.get_team_prediction(team)
print(f"\n{prediction}")
print("-" * 40)
# 3. 可视化展示
print("\n正在生成可视化图表...")
for team in ['曼城', '利物浦']:
analyzer.visualize_team_form(team)
# 4. 状态对比预测
print("\n" + "=" * 60)
print("⚖️ 球队状态对比")
print("=" * 60)
team1, team2 = '曼城', '利物浦'
m1 = analyzer.calculate_form_metrics(team1)
m2 = analyzer.calculate_form_metrics(team2)
print(f"\n{team1} vs {team2} 状态对比:")
print(f"{team1}: 评分{m1['form_score']} 场均进球{m1['avg_goals_for']} 场均失球{m1['avg_goals_against']}")
print(f"{team2}: 评分{m2['form_score']} 场均进球{m2['avg_goals_for']} 场均失球{m2['avg_goals_against']}")
if m1['form_score'] > m2['form_score']:
print(f"\n预测:{team1}状态更好,有较大优势!")
elif m1['form_score'] < m2['form_score']:
print(f"\n预测:{team2}状态更好,有较大优势!")
else:
print("\n预测:两队状态相当,比赛可能很胶着!")
if __name__ == "__main__":
main()
功能特点
多维度分析
- 胜率统计
- 场均进球/失球
- 射门效率
- 控球率
- 状态评分
智能评分系统
- 按比赛时间权重计算
- 考虑进攻和防守表现
- 综合多个指标得出状态分数
可视化展示
- 进球失球趋势图
- 控球率变化
- 射门效率柱状图
- 战绩分布饼图
预测功能
- 状态对比分析
- 胜负概率预测
- 优劣势评估
使用方法
# 基础用法
analyzer = TeamFormAnalyzer()
# 查看所有球队排名
all_teams = analyzer.analyze_all_teams()
# 查看单个球队状态
prediction = analyzer.get_team_prediction('曼城')
# 可视化球队表现
analyzer.visualize_team_form('利物浦')
这个案例可以根据实际需求扩展,比如接入真实的比赛数据API,或者添加更多分析维度(如伤病情况、主客场优势等)。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播