python案例看好的球队近期状态如何?

wen python案例 5

本文目录导读:

python案例看好的球队近期状态如何?

  1. 方法1:从CSV文件分析球队状态
  2. 方法2:从API获取实时数据(以足球为例)
  3. 方法3:多维度状态评估系统
  4. 方法4:简易可视化仪表盘
  5. 使用方法:

我来帮你创建几个Python案例来分析球队的近期状态,这里提供几个实用的方法:

方法1:从CSV文件分析球队状态

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
# 创建示例比赛数据
def create_sample_data():
    data = {
        'date': pd.date_range(end=datetime.now(), periods=30, freq='D'),
        'team': ['主队'] * 15 + ['客队'] * 15,
        'goals_for': [2, 1, 3, 0, 2, 1, 3, 2, 1, 2, 0, 3, 2, 1, 2] + [1, 0, 2, 1, 3, 0, 1, 2, 0, 1, 2, 1, 0, 2, 1],
        'goals_against': [1, 0, 1, 2, 1, 1, 0, 1, 2, 0, 1, 2, 1, 0, 1] + [0, 1, 1, 0, 2, 1, 3, 1, 1, 0, 0, 2, 1, 1, 2]
    }
    df = pd.DataFrame(data)
    return df
def analyze_team_form(df, team_name, recent_n=5):
    """分析球队近期状态"""
    # 筛选球队数据
    team_df = df[df['team'] == team_name].sort_values('date')
    # 取最近N场比赛
    recent = team_df.tail(recent_n).copy()
    # 计算胜平负
    results = []
    for _, match in recent.iterrows():
        if match['goals_for'] > match['goals_against']:
            results.append('胜')
        elif match['goals_for'] == match['goals_against']:
            results.append('平')
        else:
            results.append('负')
    recent['result'] = results
    # 统计指标
    stats = {
        '胜场': results.count('胜'),
        '平场': results.count('平'),
        '负场': results.count('负'),
        '胜率': results.count('胜') / recent_n * 100,
        '进球数': recent['goals_for'].sum(),
        '失球数': recent['goals_against'].sum(),
        '场均进球': recent['goals_for'].mean(),
        '场均失球': recent['goals_against'].mean()
    }
    # 积分计算(胜3分,平1分)
    stats['积分'] = stats['胜场'] * 3 + stats['平场']
    return recent, stats
def visualize_form(recent_df, team_name):
    """可视化球队近期状态"""
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    # 进球趋势图
    axes[0].plot(range(len(recent_df)), recent_df['goals_for'], 'o-', label='进球')
    axes[0].plot(range(len(recent_df)), recent_df['goals_against'], 's-', label='失球')
    axes[0].set_xlabel('比赛场次')
    axes[0].set_ylabel('进球数')
    axes[0].set_title(f'{team_name} 近期进球/失球趋势')
    axes[0].legend()
    axes[0].grid(True)
    # 结果分布饼图
    results = recent_df['result'].value_counts()
    colors = ['green', 'yellow', 'red']
    axes[1].pie(results, labels=results.index, autopct='%1.1f%%', colors=colors[:len(results)])
    axes[1].set_title(f'{team_name} 近期比赛结果分布')
    plt.tight_layout()
    plt.show()
# 使用示例
df = create_sample_data()
team_name = '主队'
recent_matches, team_stats = analyze_team_form(df, team_name)
print(f"=== {team_name} 近期状态 ===")
print(f"近5场比赛:{' '.join(recent_matches['result'].tolist())}")
print(f"胜: {team_stats['胜场']} 平: {team_stats['平场']} 负: {team_stats['负场']}")
print(f"胜率: {team_stats['胜率']:.1f}%")
print(f"总进球: {team_stats['进球数']} 总失球: {team_stats['失球数']}")
print(f"场均进球: {team_stats['场均进球']:.1f} 场均失球: {team_stats['场均失球']:.1f}")
print(f"积分: {team_stats['积分']}")
# 可视化
visualize_form(recent_matches, team_name)

方法2:从API获取实时数据(以足球为例)

import requests
import json
from datetime import datetime, timedelta
def fetch_team_data(api_key, team_id):
    """从API获取球队数据(示例使用足球数据API)"""
    headers = {'X-Auth-Token': api_key}
    # 获取球队近期的比赛
    url = f"https://api.football-data.org/v4/teams/{team_id}/matches"
    params = {
        'limit': 5,
        'status': 'FINISHED'
    }
    try:
        response = requests.get(url, headers=headers, params=params)
        if response.status_code == 200:
            return response.json()
        else:
            print(f"API请求失败: {response.status_code}")
            return None
    except Exception as e:
        print(f"请求出错: {e}")
        return None
def analyze_api_results(matches_data):
    """分析从API获取的比赛数据"""
    if not matches_data or 'matches' not in matches_data:
        return None
    matches = matches_data['matches']
    results = []
    for match in matches:
        home_goals = match['score']['fullTime']['home']
        away_goals = match['score']['fullTime']['away']
        # 判断主客场
        home_team = match['homeTeam']['name']
        away_team = match['awayTeam']['name']
        # 计算比赛结果
        if home_goals > away_goals:
            result = '胜' if home_team else '负'
        elif home_goals == away_goals:
            result = '平'
        else:
            result = '负' if home_team else '胜'
        results.append({
            'date': match['utcDate'][:10],
            'home': home_team,
            'away': away_team,
            'score': f'{home_goals}-{away_goals}',
            'result': result
        })
    return results

方法3:多维度状态评估系统

import numpy as np
from collections import deque
class TeamFormAnalyzer:
    """多维度的球队状态分析器"""
    def __init__(self, team_name):
        self.team_name = team_name
        self.matches = deque(maxlen=10)  # 保存最近10场比赛
    def add_match(self, goals_for, goals_against, opponent_strength=0.5):
        """添加一场比赛记录
        opponent_strength: 对手强度 (0-1,1为最强)
        """
        self.matches.append({
            'goals_for': goals_for,
            'goals_against': goals_against,
            'result': 3 if goals_for > goals_against else (1 if goals_for == goals_against else 0),
            'opponent': opponent_strength
        })
    def calculate_form_score(self):
        """计算综合状态评分 (0-100)"""
        if not self.matches:
            return 0
        scores = []
        weights = [0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 1.0]
        for i, match in enumerate(self.matches):
            # 1. 结果得分 (40%)
            result_score = match['result'] * 33.3/3
            # 2. 进攻得分 (30%)
            attack_score = min(match['goals_for'] / 3, 1) * 100
            # 3. 防守得分 (20%)
            defense_score = max(1 - match['goals_against'] / 3, 0) * 100
            # 4. 对手强度得分 (10%)
            opponent_score = match['opponent'] * 100
            # 加权总分
            match_score = (result_score * 0.4 + 
                          attack_score * 0.3 + 
                          defense_score * 0.2 + 
                          opponent_score * 0.1)
            # 应用时间权重(近期比赛权重更高)
            match_score *= weights[len(self.matches)-1-i]
            scores.append(match_score)
        # 归一化
        total_score = sum(scores) / sum(weights) if scores else 0
        return min(total_score, 100)
    def get_form_status(self):
        """获取状态等级"""
        score = self.calculate_form_score()
        if score >= 80:
            return f"🔥 状态火热 ({score:.1f}分)"
        elif score >= 60:
            return f"✅ 状态良好 ({score:.1f}分)"
        elif score >= 40:
            return f"⚠️ 状态一般 ({score:.1f}分)"
        else:
            return f"❄️ 状态低迷 ({score:.1f}分)"
    def predict_next_outcome(self):
        """预测下一场比赛"""
        if len(self.matches) < 3:
            return "数据不足,无法预测"
        recent_results = [m['result'] for m in self.matches]
        recent_gf = [m['goals_for'] for m in self.matches]
        recent_ga = [m['goals_against'] for m in self.matches]
        avg_gf = np.mean(recent_gf)
        avg_ga = np.mean(recent_ga)
        form_score = self.calculate_form_score()
        # 简单概率预测
        win_prob = 0.3 + (form_score / 100) * 0.3 + (avg_gf - avg_ga) * 0.05
        win_prob = max(0.1, min(0.8, win_prob))
        draw_prob = 0.2 * (1 - abs(avg_gf - avg_ga) / 3)
        return {
            'win_probability': win_prob,
            'draw_probability': draw_prob,
            'lose_probability': 1 - win_prob - draw_prob,
            'expected_goals_for': avg_gf,
            'expected_goals_against': avg_ga
        }
# 使用示例
analyzer = TeamFormAnalyzer("示例球队")
# 模拟添加比赛
matches_data = [
    (3, 1, 0.8),  # (进球, 失球, 对手强度)
    (2, 0, 0.6),
    (1, 1, 0.5),
    (3, 2, 0.7),
    (0, 1, 0.9),
    (2, 2, 0.4),
    (4, 1, 0.3),
    (1, 0, 0.8),
    (2, 1, 0.7),
    (3, 0, 0.5)
]
for gf, ga, opp in matches_data:
    analyzer.add_match(gf, ga, opp)
# 输出分析结果
print(f"球队: {analyzer.team_name}")
print(f"状态评定: {analyzer.get_form_status()}")
print(f"综合评分: {analyzer.calculate_form_score():.2f}")
# 预测下一场
prediction = analyzer.predict_next_outcome()
print("\n下一场比赛预测:")
print(f"胜: {prediction['win_probability']*100:.1f}%")
print(f"平: {prediction['draw_probability']*100:.1f}%")
print(f"负: {prediction['lose_probability']*100:.1f}%")
print(f"预期进球: {prediction['expected_goals_for']:.1f} - 预期失球: {prediction['expected_goals_against']:.1f}")

方法4:简易可视化仪表盘

import dash
from dash import dcc, html
import plotly.graph_objects as go
import pandas as pd
def create_form_dashboard(teams_data, teams_names):
    """创建球队状态仪表盘"""
    app = dash.Dash(__name__)
    fig = go.Figure()
    # 为每支球队添加状态曲线
    for i, team_data in enumerate(teams_data):
        results = ['胜', '平', '负', '胜', '平', '胜', '负', '胜', '胜', '平']
        scores = [3, 1, 0, 3, 1, 3, 0, 3, 3, 1]  # 积分
        fig.add_trace(go.Scatter(
            x=list(range(1, len(scores)+1)),
            y=scores,
            mode='lines+markers',
            name=teams_names[i],
            line=dict(width=2)
        ))
    fig.update_layout(
        title='球队近期状态对比',
        xaxis_title='比赛场次',
        yaxis_title='积分',
        showlegend=True
    )
    app.layout = html.Div(children=[
        html.H1(children='球队状态分析'),
        dcc.Graph(
            id='team-form-graph',
            figure=fig
        ),
        html.Div(id='team-stats')
    ])
    return app
# 使用示例
teams_data = [
    [3, 1, 0, 3, 1, 0, 3, 3, 1, 0],
    [0, 3, 1, 0, 3, 1, 0, 3, 1, 3]
]
teams_names = ['主队', '客队']
# app = create_form_dashboard(teams_data, teams_names)
# app.run(debug=True)

使用方法:

  1. 方法1:适合分析本地保存的比赛数据
  2. 方法2:通过API获取实时数据
  3. 方法3:最全面的多维度状态评估系统
  4. 方法4:可视化的仪表盘展示

这个系统可以帮你:

  • 快速评估球队近期胜率
  • 分析进攻和防守表现
  • 预测下一场比赛结果
  • 可视化展示状态变化趋势

需要根据你的具体需求选择合适的方法!

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