Python 案例:赛季累计数据对比统计
下面通过一个完整的案例,演示如何用 Python 统计并对比球员/球队的赛季累计数据。

案例场景
假设我们有 NBA 球员逐场数据,需要:
- 统计每位球员赛季累计数据(得分、篮板、助攻等)
- 计算场均数据
- 对比不同球员表现
- 可视化对比结果
完整代码实现
构造示例数据
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
# 模拟逐场数据
np.random.seed(42)
games = 20 # 每赛季20场
data = []
players = ['詹姆斯', '库里', '杜兰特', '字母哥']
for player in players:
for game in range(1, games + 1):
data.append({
'球员': player,
'场次': game,
'得分': np.random.randint(15, 40),
'篮板': np.random.randint(3, 15),
'助攻': np.random.randint(2, 12),
'抢断': np.random.randint(0, 5),
'盖帽': np.random.randint(0, 4),
'失误': np.random.randint(0, 6),
'上场时间': np.random.randint(25, 40)
})
df = pd.DataFrame(data)
print(df.head())
统计赛季累计数据
# 按球员分组,统计累计和场均数据
summary = df.groupby('球员').agg(
出场次数=('场次', 'count'),
总得分=('得分', 'sum'),
总篮板=('篮板', 'sum'),
总助攻=('助攻', 'sum'),
总抢断=('抢断', 'sum'),
总盖帽=('盖帽', 'sum'),
总失误=('失误', 'sum'),
总时间=('上场时间', 'sum'),
).reset_index()
# 计算场均
summary['场均得分'] = (summary['总得分'] / summary['出场次数']).round(2)
summary['场均篮板'] = (summary['总篮板'] / summary['出场次数']).round(2)
summary['场均助攻'] = (summary['总助攻'] / summary['出场次数']).round(2)
summary['场均时间'] = (summary['总时间'] / summary['出场次数']).round(2)
# 计算效率值 PER 简化版
summary['效率值'] = (
summary['总得分'] + summary['总篮板'] + summary['总助攻']
+ summary['总抢断'] + summary['总盖帽'] - summary['总失误']
) / summary['出场次数']
summary['效率值'] = summary['效率值'].round(2)
print(summary)
输出示例:
| 球员 | 出场次数 | 总得分 | 总篮板 | 总助攻 | 场均得分 | 场均篮板 | 场均助攻 | 效率值 |
|---|---|---|---|---|---|---|---|---|
| 字母哥 | 20 | 542 | 178 | 132 | 10 | 90 | 60 | 8 |
| 库里 | 20 | 528 | 165 | 145 | 40 | 25 | 25 | 2 |
| 杜兰特 | 20 | 545 | 170 | 128 | 25 | 50 | 40 | 5 |
| 詹姆斯 | 20 | 520 | 175 | 140 | 00 | 75 | 00 | 0 |
多赛季累计对比
如果有多个赛季的数据,可以按赛季 + 球员分组:
# 模拟多赛季数据
data_multi = []
seasons = ['2022-23', '2023-24', '2024-25']
for season in seasons:
for player in players:
for game in range(1, games + 1):
data_multi.append({
'赛季': season,
'球员': player,
'得分': np.random.randint(15, 40),
'篮板': np.random.randint(3, 15),
'助攻': np.random.randint(2, 12),
})
df_m = pd.DataFrame(data_multi)
# 按赛季 + 球员统计累计
season_summary = df_m.groupby(['赛季', '球员']).agg(
总得分=('得分', 'sum'),
总篮板=('篮板', 'sum'),
总助攻=('助攻', 'sum'),
场次=('得分', 'count')
).reset_index()
season_summary['场均得分'] = (season_summary['总得分'] / season_summary['场次']).round(2)
print(season_summary)
# 透视表:球员 vs 赛季的累计得分对比
pivot = season_summary.pivot(index='球员', columns='赛季', values='总得分')
print("\n各赛季累计得分对比:")
print(pivot)
# 计算赛季间增长率
pivot['增长率'] = ((pivot['2024-25'] - pivot['2022-23']) / pivot['2022-23'] * 100).round(2)
print("\n相比首赛季增长率(%):")
print(pivot['增长率'])
可视化对比
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 图1:场均数据分组柱状图
metrics = ['场均得分', '场均篮板', '场均助攻']
x = np.arange(len(players))
width = 0.25
for i, metric in enumerate(metrics):
axes[0].bar(x + i * width, summary[metric], width, label=metric)
axes[0].set_xticks(x + width)
axes[0].set_xticklabels(summary['球员'])
axes[0].set_title('球员场均数据对比')
axes[0].legend()
axes[0].grid(axis='y', alpha=0.3)
# 图2:赛季累计得分趋势
for player in players:
player_data = season_summary[season_summary['球员'] == player]
axes[1].plot(player_data['赛季'], player_data['总得分'], marker='o', label=player)
axes[1].set_title('各赛季累计得分趋势')
axes[1].set_xlabel('赛季')
axes[1].set_ylabel('累计得分')
axes[1].legend()
axes[1].grid(alpha=0.3)
plt.tight_layout()
plt.show()
雷达图对比(更直观)
from math import pi
# 归一化数据
categories = ['场均得分', '场均篮板', '场均助攻', '效率值']
N = len(categories)
angles = [n / float(N) * 2 * pi for n in range(N)]
angles += angles[:1]
fig, ax = plt.subplots(figsize=(7, 7), subplot_kw=dict(polar=True))
# 归一化
norm = summary.copy()
for c in categories:
norm[c] = norm[c] / norm[c].max()
for _, row in norm.iterrows():
values = row[categories].tolist()
values += values[:1]
ax.plot(angles, values, linewidth=2, label=row['球员'])
ax.fill(angles, values, alpha=0.15)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories)
ax.set_title('球员综合能力对比雷达图', y=1.08)
ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
plt.show()
核心技巧总结
| 步骤 | 关键方法 | 说明 |
|---|---|---|
| 分组统计 | groupby().agg() |
一次算出多个累计值 |
| 派生指标 | 列运算 | 场均 = 总量 / 场次 |
| 多维度对比 | pivot() |
球员×赛季透视表 |
| 增长率 | 差值/基期 | 赛季间变化 |
| 可视化 | bar / line / radar | 多角度对比 |
拓展方向
- 对比两队:把"球员"换成"球队",对比攻防数据
- 加入排名:
rank()计算各指标联盟排名 - 同比增长:
pct_change()计算赛季环比 - 加权评分:自定义权重算出综合实力分
- 动态图表:用 Plotly 做交互式对比
# 排名示例 summary['得分排名'] = summary['场均得分'].rank(ascending=False).astype(int) summary['综合排名'] = summary['效率值'].rank(ascending=False).astype(int) print(summary[['球员', '得分排名', '综合排名']])
如果你有真实的赛季数据(Excel/CSV)或具体想对比的指标(如真实命中率、正负值等),可以发给我,我帮你写针对性的统计脚本。