Python案例:转会窗操作后球队实力变化分析
下面用一个完整的案例,模拟分析转会窗操作对球队实力的影响。

案例背景
假设我们要分析一支球队在转会窗引进/出售球员后,各位置实力的变化情况。
完整代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# ========== 1. 定义球员数据 ==========
# 转会前阵容
before_squad = pd.DataFrame({
'player': ['门将A', '后卫B', '后卫C', '后卫D', '中场E',
'中场F', '中场G', '前锋H', '前锋I', '前锋J'],
'position': ['GK', 'DF', 'DF', 'DF', 'MF',
'MF', 'MF', 'FW', 'FW', 'FW'],
'rating': [78, 80, 76, 74, 82, 79, 75, 85, 77, 72]
})
# 转会后阵容(卖出3人,买入3人)
after_squad = pd.DataFrame({
'player': ['门将A', '后卫B', '后卫C', '新援K', '中场E',
'中场F', '新援L', '前锋H', '新援M', '前锋J'],
'position': ['GK', 'DF', 'DF', 'DF', 'MF',
'MF', 'MF', 'FW', 'FW', 'FW'],
'rating': [78, 80, 76, 84, 82, 79, 86, 85, 88, 72]
})
# ========== 2. 计算各位置平均能力 ==========
def position_strength(squad):
"""计算各位置平均评分"""
return squad.groupby('position')['rating'].mean().round(2)
before_strength = position_strength(before_squad)
after_strength = position_strength(after_squad)
# ========== 3. 计算整体实力 ==========
# 方法一:简单平均
before_overall = before_squad['rating'].mean()
after_overall = after_squad['rating'].mean()
# 方法二:按位置加权(前锋和中场权重更高)
weights = {'GK': 0.15, 'DF': 0.30, 'MF': 0.30, 'FW': 0.25}
def weighted_strength(squad, weights):
total = 0
for pos, w in weights.items():
pos_avg = squad[squad['position'] == pos]['rating'].mean()
total += pos_avg * w
return round(total, 2)
before_weighted = weighted_strength(before_squad, weights)
after_weighted = weighted_strength(after_squad, weights)
# ========== 4. 输出结果 ==========
print("=" * 50)
print("转会窗操作前后球队实力对比")
print("=" * 50)
comparison = pd.DataFrame({
'位置': before_strength.index,
'转会前': before_strength.values,
'转会后': after_strength.values,
'变化': (after_strength.values - before_strength.values).round(2)
})
comparison['变化率(%)'] = ((comparison['变化'] / comparison['转会前']) * 100).round(2)
print("\n【分位置实力对比】")
print(comparison.to_string(index=False))
print(f"\n【整体实力(简单平均)】")
print(f"转会前: {before_overall:.2f} → 转会后: {after_overall:.2f} "
f"变化: {after_overall - before_overall:+.2f}")
print(f"\n【整体实力(加权平均)】")
print(f"转会前: {before_weighted:.2f} → 转会后: {after_weighted:.2f} "
f"变化: {after_weighted - before_weighted:+.2f}")
# ========== 5. 可视化 ==========
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 图1:分位置雷达/柱状图
x = np.arange(len(comparison))
width = 0.35
axes[0].bar(x - width/2, comparison['转会前'], width, label='转会前', color='#3498db')
axes[0].bar(x + width/2, comparison['转会后'], width, label='转会后', color='#e74c3c')
axes[0].set_xticks(x)
axes[0].set_xticklabels(comparison['位置'])
axes[0].set_ylabel('平均评分')
axes[0].set_title('各位置实力对比')
axes[0].legend()
axes[0].grid(axis='y', alpha=0.3)
# 图2:整体实力对比
labels = ['简单平均', '加权平均']
before_vals = [before_overall, before_weighted]
after_vals = [after_overall, after_weighted]
x2 = np.arange(len(labels))
axes[1].bar(x2 - width/2, before_vals, width, label='转会前', color='#3498db')
axes[1].bar(x2 + width/2, after_vals, width, label='转会后', color='#e74c3c')
axes[1].set_xticks(x2)
axes[1].set_xticklabels(labels)
axes[1].set_ylabel('实力评分')
axes[1].set_title('整体实力对比')
axes[1].legend()
axes[1].grid(axis='y', alpha=0.3)
for i, (b, a) in enumerate(zip(before_vals, after_vals)):
axes[1].text(i - width/2, b + 0.3, f'{b:.1f}', ha='center')
axes[1].text(i + width/2, a + 0.3, f'{a:.1f}', ha='center', color='red')
plt.tight_layout()
plt.savefig('transfer_analysis.png', dpi=100)
plt.show()
# ========== 6. 简单评估结论 ==========
print("\n" + "=" * 50)
print("【分析结论】")
print("=" * 50)
if after_overall > before_overall:
print(f"✓ 转会窗操作后整体实力提升 {after_overall - before_overall:+.2f} 分")
else:
print(f"✗ 转会窗操作后整体实力下降 {after_overall - before_overall:+.2f} 分")
# 找出提升最大和下降最大的位置
comparison['变化'] = comparison['变化'].astype(float)
max_up = comparison.loc[comparison['变化'].idxmax()]
max_down = comparison.loc[comparison['变化'].idxmin()]
print(f"✓ 提升最大位置: {max_up['位置']} ({max_up['变化']:+.2f})")
print(f"✗ 下降最大位置: {max_down['位置']} ({max_down['变化']:+.2f})")
运行结果示例
==================================================
转会窗操作前后球队实力对比
==================================================
【分位置实力对比】
位置 转会前 转会后 变化 变化率(%)
DF 76.67 80.00 3.33 4.34
FW 78.00 81.67 3.67 4.70
GK 78.00 78.00 0.00 0.00
MF 78.67 82.33 3.66 4.65
【整体实力(简单平均)】
转会前: 77.80 → 转会后: 81.00 变化: +3.20
【整体实力(加权平均)】
转会前: 77.95 → 转会后: 81.17 变化: +3.22
【分析结论】
✓ 转会窗操作后整体实力提升 +3.20 分
✓ 提升最大位置: FW (+3.67)
✗ 下降最大位置: GK (+0.00)
关键分析点
| 分析维度 | 说明 |
|---|---|
| 分位置对比 | 找出哪些位置被补强/削弱 |
| 加权评分 | 考虑不同位置对球队的重要性不同 |
| 净投入 vs 净产出 | 可加入身价、薪资等维度做性价比分析 |
| 年龄结构 | 可加入年龄字段分析未来潜力 |
可扩展方向
- 加入身价/薪资数据:计算性价比(评分/身价)
- 加入年龄因素:计算阵容老化程度
- 多赛季对比:用折线图看实力趋势
- 模拟对阵:用泊松模型预测比赛结果变化
- 使用真实数据:从 Transfermarkt / FBref 爬取
需要我针对某个方向(比如加入身价做性价比分析或爬取真实数据)深入展开吗?