用Python分析球队近期状态案例
下面给你一个完整的实战案例,分析一支球队(以英超为例)的近期状态,我会分几个层次讲,从数据获取到可视化再到状态评分。

方案设计思路
分析球队"近期状态",通常关注这几个维度:
| 维度 | 说明 |
|---|---|
| 胜平负走势 | 最近5-10场结果 |
| 进失球 | 进攻/防守状态 |
| 对手强度 | 赢强队 vs 赢弱队含金量不同 |
| 主客场 | 分开看 |
| 状态趋势 | 是上升还是下滑 |
数据获取(两种方式)
方式1:免费API(football-data.org)
import requests
import pandas as pd
API_KEY = "你的API_KEY" # 免费注册获取
headers = {"X-Auth-Token": API_KEY}
# 获取英超某队最近比赛
team_id = 57 # 阿森纳
url = f"https://api.football-data.org/v4/teams/{team_id}/matches?status=FINISHED&limit=10"
resp = requests.get(url, headers=headers)
data = resp.json()
matches = []
for m in data["matches"]:
matches.append({
"date": m["utcDate"][:10],
"home": m["homeTeam"]["name"],
"away": m["awayTeam"]["name"],
"home_goals": m["score"]["fullTime"]["home"],
"away_goals": m["score"]["fullTime"]["away"],
"competition": m["competition"]["name"]
})
df = pd.DataFrame(matches)
print(df.tail(10))
方式2:爬虫(需遵守网站robots协议)
如果API受限,可从公开数据站(如 FBref、SofaScore)抓取,注意加请求头、控制频率。
状态评分模型(核心)
def analyze_form(df, team_name, recent_n=8):
"""计算球队近期状态综合分"""
recent = df.tail(recent_n).copy()
# 判断主客场并计算胜负
def get_result(row):
if row["home"] == team_name:
gf, ga = row["home_goals"], row["away_goals"]
else:
gf, ga = row["away_goals"], row["home_goals"]
return gf, ga
recent[["gf", "ga"]] = recent.apply(
lambda r: pd.Series(get_result(r)), axis=1
)
recent["points"] = recent.apply(
lambda r: 3 if r["gf"] > r["ga"] else (1 if r["gf"] == r["ga"] else 0), axis=1
)
# 加权:越近的比赛权重越高
weights = [i+1 for i in range(len(recent))]
weighted_pts = sum(p*w for p, w in zip(recent["points"], weights)) / sum(weights)
# 攻防数据
avg_gf = recent["gf"].mean()
avg_ga = recent["ga"].mean()
win_rate = (recent["points"] == 3).mean()
# 综合评分(0-10)
form_score = (
weighted_pts / 3 * 4 + # 积分权重
min(avg_gf / 2.5, 1) * 3 + # 进攻
max(0, 1 - avg_ga / 2.5) * 3 # 防守
)
return {
"球队": team_name,
"近N场": recent_n,
"加权积分率": round(weighted_pts/3, 2),
"胜率": f"{win_rate:.0%}",
"场均进球": round(avg_gf, 2),
"场均失球": round(avg_ga, 2),
"状态评分": round(form_score, 2),
"趋势": "↑上升" if recent["points"].iloc[-3:].mean() > recent["points"].iloc[:3].mean() else "↓下滑或平稳"
}
result = analyze_form(df, "Arsenal")
for k, v in result.items():
print(f"{k}: {v}")
输出示例:
球队: Arsenal
近N场: 8
加权积分率: 0.79
胜率: 63%
场均进球: 2.13
场均失球: 0.88
状态评分: 7.85
趋势: ↑上升
可视化(状态一目了然)
import matplotlib.pyplot as plt
def plot_form(df, team_name, recent_n=10):
recent = df.tail(recent_n).copy()
recent["result"] = recent.apply(
lambda r: "W" if (r["home"]==team_name and r["home_goals"]>r["away_goals"])
or (r["away"]==team_name and r["away_goals"]>r["home_goals"])
else ("D" if r["home_goals"]==r["away_goals"] else "L"),
axis=1
)
color_map = {"W": "green", "D": "gray", "L": "red"}
fig, ax = plt.subplots(figsize=(10, 4))
x = range(len(recent))
for i, r in enumerate(recent["result"]):
ax.bar(i, 1, color=color_map[r])
ax.text(i, 0.5, r, ha="center", va="center",
color="white", fontsize=14, fontweight="bold")
ax.set_xticks(list(x))
ax.set_xticklabels(recent["date"], rotation=45)
ax.set_yticks([])
ax.set_title(f"{team_name} 近{recent_n}场战绩")
plt.tight_layout()
plt.savefig("form.png")
plt.show()
进阶:横向对比多支球队
teams = ["Arsenal", "Man City", "Liverpool", "Chelsea"]
comparison = pd.DataFrame([analyze_form(df_all, t) for t in teams])
comparison = comparison.sort_values("状态评分", ascending=False)
print(comparison.to_string(index=False))
注意事项
- 数据时效性:比赛数据要实时更新,建议每天定时抓取。
- 样本量:至少5场以上才有统计意义,少于3场噪音很大。
- 对手质量:进阶版应给对手加难度系数(如打败榜首 vs 打败榜尾含金量不同),可结合联赛排名做加权。
- 赛程密度/伤病:真实状态要结合球员伤停、欧战多线作战等因素,纯数据模型只能反映部分。
- 合规:API用官方免费额度即可,爬虫务必遵守 robots 协议和频率限制。
需要我帮你针对某个具体联赛/球队(比如中超、欧冠、某支你关注的队)定制这套代码吗?或者加上对手强度加权、主客场拆分、xG(预期进球) 这类进阶指标?