本文目录导读:

这是一个很有意思的案例分析题,我们可以用Python来做一次数据驱动的复盘,量化“主力伤退”对球队的影响,下面我用一个模拟的NBA场景来演示完整的分析框架。
案例背景设定
假设我们分析某支球队(比如勇士队)在某个赛季中,核心球员(比如库里)因伤缺阵的比赛,与他在场时的比赛表现差异。
完整Python分析代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
# ============================================
# 1. 构造模拟数据(实际中从数据库/API获取)
# ============================================
np.random.seed(42)
# 模拟一个赛季82场比赛
n_games = 82
games = pd.DataFrame({
'game_id': range(1, n_games+1),
'date': pd.date_range('2023-10-01', periods=n_games, freq='2D'),
})
# 主力在场时的球队表现(真实水平)
games['star_played'] = np.random.choice([1, 0], size=n_games, p=[0.8, 0.2]) # 80%出场率
# 得分模拟:主力在场 vs 缺阵
games['team_score'] = np.where(
games['star_played'] == 1,
np.random.normal(115, 8, n_games), # 在场:场均115分
np.random.normal(105, 9, n_games) # 缺阵:场均105分
).round().astype(int)
games['opp_score'] = np.random.normal(110, 8, n_games).round().astype(int)
games['win'] = (games['team_score'] > games['opp_score']).astype(int)
# 主力个人数据
games['star_points'] = np.where(
games['star_played'] == 1,
np.random.normal(28, 5, n_games),
0
).round()
# ============================================
# 2. 核心对比分析
# ============================================
print("=" * 60)
print("【一、基础对比:主力在场 vs 缺阵】")
print("=" * 60)
summary = games.groupby('star_played').agg({
'team_score': ['mean', 'std'],
'opp_score': 'mean',
'win': ['sum', 'mean'], # 胜场数、胜率
'game_id': 'count'
}).round(2)
summary.columns = ['场均得分', '得分标准差', '场均失分', '胜场数', '胜率', '比赛场次']
summary.index = ['主力缺阵', '主力在场']
print(summary)
# 计算影响幅度
played = games[games['star_played'] == 1]
absent = games[games['star_played'] == 0]
score_diff = played['team_score'].mean() - absent['team_score'].mean()
winrate_diff = played['win'].mean() - absent['win'].mean()
print(f"\n📊 关键影响指标:")
print(f" 得分影响:主力在场时场均多得 {score_diff:.1f} 分")
print(f" 胜率影响:胜率变化 {winrate_diff*100:+.1f} 个百分点")
print(f" (在场胜率 {played['win'].mean()*100:.1f}% vs 缺阵胜率 {absent['win'].mean()*100:.1f}%)")
# ============================================
# 3. 统计显著性检验
# ============================================
print("\n" + "=" * 60)
print("【二、统计显著性检验】")
print("=" * 60)
# t检验:得分差异是否显著
t_stat, p_value = stats.ttest_ind(played['team_score'], absent['team_score'])
print(f"得分差异 t检验:t={t_stat:.3f}, p={p_value:.4f}")
print(f" → {'差异显著(p<0.05)' if p_value < 0.05 else '差异不显著'}")
# 胜率的卡方检验
contingency = pd.crosstab(games['star_played'], games['win'])
chi2, p_chi, _, _ = stats.chi2_contingency(contingency)
print(f"胜率差异 卡方检验:chi2={chi2:.3f}, p={p_chi:.4f}")
print(f" → {'差异显著(p<0.05)' if p_chi < 0.05 else '差异不显著'}")
# 效应量 Cohen's d
pooled_std = np.sqrt(((len(played)-1)*played['team_score'].std()**2 +
(len(absent)-1)*absent['team_score'].std()**2) /
(len(played)+len(absent)-2))
cohens_d = (played['team_score'].mean() - absent['team_score'].mean()) / pooled_std
print(f"效应量 Cohen's d = {cohens_d:.3f}")
print(f" → {'大效应' if abs(cohens_d)>0.8 else '中等效应' if abs(cohens_d)>0.5 else '小效应'}")
# ============================================
# 4. 可视化
# ============================================
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
# 图1:得分分布
axes[0].hist(played['team_score'], bins=15, alpha=0.6, label='主力在场', color='green')
axes[0].hist(absent['team_score'], bins=15, alpha=0.6, label='主力缺阵', color='red')
axes[0].axvline(played['team_score'].mean(), color='green', linestyle='--')
axes[0].axvline(absent['team_score'].mean(), color='red', linestyle='--')
axes[0].set_title('球队得分分布对比')
axes[0].set_xlabel('得分')
axes[0].legend()
# 图2:胜率对比
win_rates = [absent['win'].mean()*100, played['win'].mean()*100]
axes[1].bar(['主力缺阵', '主力在场'], win_rates, color=['red', 'green'])
for i, v in enumerate(win_rates):
axes[1].text(i, v+1, f'{v:.1f}%', ha='center', fontweight='bold')
axes[1].set_ylabel('胜率 (%)')
axes[1].set_title('胜率对比')
axes[1].set_ylim(0, 100)
# 图3:逐场得分走势
axes[2].plot(games['game_id'], games['team_score'], marker='o', markersize=3, linewidth=1)
absent_games = games[games['star_played']==0]
axes[2].scatter(absent_games['game_id'], absent_games['team_score'],
color='red', s=80, zorder=5, label='主力缺阵场次')
axes[2].set_title('赛季得分走势')
axes[2].set_xlabel('比赛场次')
axes[2].set_ylabel('得分')
axes[2].legend()
plt.tight_layout()
plt.savefig('star_impact_analysis.png', dpi=100, bbox_inches='tight')
plt.show()
# ============================================
# 5. 进阶:控制变量分析
# ============================================
print("\n" + "=" * 60)
print("【三、进阶:区分对手强弱后的影响】")
print("=" * 60)
# 根据对手场均失分划分对手强弱(模拟)
games['opp_strength'] = pd.cut(games['opp_score'],
bins=[0, 105, 115, 200],
labels=['强队', '中游', '弱队'])
pivot = games.pivot_table(values='win', index='opp_strength',
columns='star_played', aggfunc='mean') * 100
pivot.columns = ['主力缺阵胜率', '主力在场胜率']
pivot['胜率差值'] = pivot['主力在场胜率'] - pivot['主力缺阵胜率']
print(pivot.round(1))
# 结论输出
print("\n" + "=" * 60)
print("【四、复盘结论】")
print("=" * 60)
print(f"""
1. 【进攻影响】主力缺阵导致场均得分下降 {score_diff:.1f} 分({score_diff/played['team_score'].mean()*100:.1f}%)
2. 【战绩影响】胜率从 {played['win'].mean()*100:.1f}% 降至 {absent['win'].mean()*100:.1f}%,
相当于每10场少赢 {winrate_diff*10:.1f} 场
3. 【统计显著性】得分差异 p={p_value:.4f},{'显著' if p_value<0.05 else '不显著'};
效应量 d={cohens_d:.2f},属于{'较大' if abs(cohens_d)>0.5 else '较小'}影响
4. 【对手分层】对阵强队时主力缺阵影响最大(胜率下降 {pivot.loc['强队','胜率差值']:.1f}%)
5. 【建议】主力缺阵期间需在{...}等方面补强
""".format(...) if False else f"""
1. 【进攻影响】主力缺阵导致场均得分下降 {score_diff:.1f} 分({score_diff/played['team_score'].mean()*100:.1f}%)
2. 【战绩影响】胜率从 {played['win'].mean()*100:.1f}% 降至 {absent['win'].mean()*100:.1f}%,
相当于每10场少赢 {winrate_diff*10:.1f} 场
3. 【统计显著性】得分差异 p={p_value:.4f},{'显著' if p_value<0.05 else '不显著'};
效应量 Cohen's d={cohens_d:.2f},属于{'较大' if abs(cohens_d)>0.5 else '较小'}影响
4. 【对手分层】对阵强队时主力缺阵影响最大(胜率下降 {pivot.loc['强队','胜率差值']:.1f}%)
5. 【建议】主力缺阵期间需要在进攻端补强,尤其是对阵强队时
""")
分析方法论要点
| 分析维度 | 方法 | 目的 |
|---|---|---|
| 基础对比 | 分组聚合均值 | 快速看差异 |
| 显著性检验 | t检验/卡方检验 | 差异是否偶然 |
| 效应量 | Cohen's d | 差异有多大(比p值更实用) |
| 控制变量 | 分层分析 | 排除对手强弱干扰 |
| 可视化 | 分布图+走势图 | 直观呈现 |
实战复盘的5个关键陷阱
- 样本量小:主力缺阵可能只有5-10场,统计功效不足,需用贝叶斯方法或置信区间
- 混杂因素:缺阵期间可能恰好赛程轻松/困难,需做赛程强度调整(SOS)
- 幸存者偏差:只分析已发生的比赛,忽略“如果主力在场会怎样”的反事实
- 相关性≠因果:胜率下降不全是主力缺阵导致,可能伴随其他球员状态波动
- 回音室效应:媒体渲染“缺阵影响巨大”会强化认知偏差,数据要客观
真实数据获取建议
# 真实场景可用数据源 # 1. NBA官方API: https://stats.nba.com/ # 2. basketball-reference 爬虫 # 3. Kaggle NBA数据集 # 4. 使用 nba_api 库: pip install nba_api from nba_api.stats.endpoints import leaguegamefinder # games = leaguegamefinder.LeagueGameFinder(team_id_nullable=1610612744).get_data_frames()[0]
核心结论:主力伤退的影响要分维度量化(得分/防守/胜率/关键球),配合统计检验+效应量,并控制对手强度等混杂因素,才能得出“影响到底多大”的可信结论,单纯看胜率变化容易被赛程和运气误导。
需要我针对某个具体球队/球员做调整,或者补充贝叶斯分析、反事实模拟(如用ELO模型估算“如果主力在场”的预期战绩)吗?
版权声明:本站文章为原创整理,转载请注明出处。