本文目录导读:

我将为您创建一个综合Python案例,用于分析高速跑动距离的对比,这个案例将模拟运动员在不同比赛中的高速跑动数据,并进行可视化对比。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
class HighSpeedRunningAnalyzer:
"""高速跑动距离分析器"""
def __init__(self):
"""初始化分析器"""
self.data = None
self.speed_threshold = 21 # 高速跑动速度阈值 (km/h)
def generate_sample_data(self, n_players=10, n_matches=3):
"""
生成模拟数据
参数:
- n_players: 运动员数量
- n_matches: 比赛场次
"""
np.random.seed(42)
players = [f'球员_{chr(65+i)}' for i in range(n_players)]
matches = [f'第{i+1}轮' for i in range(n_matches)]
data_list = []
for player in players:
# 每个运动员的基础跑动能力
base_speed = np.random.uniform(15, 25) # 基础高速跑动距离(米/分钟)
base_distance = np.random.uniform(800, 1200) # 基础总跑动距离
for match in matches:
# 添加随机波动
speed_factor = np.random.normal(1, 0.1)
match_factor = np.random.normal(1, 0.05)
# 计算高速跑动距离
high_speed_distance = base_distance * 0.2 * speed_factor # 20%为高速跑动
high_speed_distance = max(100, high_speed_distance) # 确保最小值
# 计算其他指标
total_distance = base_distance * match_factor
sprint_count = int(high_speed_distance / np.random.uniform(30, 50))
max_speed = np.random.uniform(28, 35)
data_list.append({
'球员': player,
'比赛': match,
'高速跑动距离': round(high_speed_distance, 1),
'总跑动距离': round(total_distance, 1),
'冲刺次数': sprint_count,
'最高速度': round(max_speed, 1),
'高速跑动占比': round(high_speed_distance / total_distance * 100, 2)
})
self.data = pd.DataFrame(data_list)
return self.data
def load_real_data(self, filepath):
"""加载真实数据"""
try:
self.data = pd.read_csv(filepath)
return self.data
except FileNotFoundError:
print(f"文件 {filepath} 未找到,请检查路径")
return None
def basic_statistics(self):
"""基础统计分析"""
if self.data is None:
print("请先生成或加载数据")
return None
print("=" * 60)
print("基础统计分析")
print("=" * 60)
# 整体统计
print("\n整体统计:")
print(self.data[['高速跑动距离', '总跑动距离', '冲刺次数', '最高速度']].describe())
# 按球员统计
print("\n按球员平均统计:")
player_stats = self.data.groupby('球员')[['高速跑动距离', '总跑动距离', '冲刺次数']].mean()
print(player_stats)
return player_stats
def player_comparison(self, top_n=5):
"""球员对比分析"""
if self.data is None:
print("请先生成或加载数据")
return None
# 计算每名球员的平均高速跑动距离
avg_high_speed = self.data.groupby('球员')['高速跑动距离'].mean().sort_values(ascending=False)
print(f"\n高速跑动距离前{top_n}名球员:")
for i, (player, distance) in enumerate(avg_high_speed.head(top_n).items(), 1):
print(f"{i}. {player}: {distance:.1f}米")
return avg_high_speed
def visualize_comparison(self):
"""可视化对比"""
if self.data is None:
print("请先生成或加载数据")
return
fig, axes = plt.subplots(3, 2, figsize=(15, 12))
fig.suptitle('高速跑动距离对比分析', fontsize=16, fontweight='bold')
# 1. 球员高速跑动距离对比(条形图)
ax1 = axes[0, 0]
player_avg = self.data.groupby('球员')['高速跑动距离'].mean().sort_values()
bars = ax1.barh(range(len(player_avg)), player_avg.values, color='skyblue', edgecolor='navy')
# 添加数据标签
for i, (v, name) in enumerate(zip(player_avg.values, player_avg.index)):
ax1.text(v + 5, i, f'{v:.0f}m', va='center', fontsize=9)
ax1.set_yticks(range(len(player_avg)))
ax1.set_yticklabels(player_avg.index)
ax1.set_xlabel('高速跑动距离 (米)')
ax1.set_title('球员平均高速跑动距离')
ax1.grid(axis='x', alpha=0.3)
# 2. 各比赛高速跑动距离对比(箱线图)
ax2 = axes[0, 1]
match_data = [self.data[self.data['比赛'] == m]['高速跑动距离'] for m in self.data['比赛'].unique()]
bp = ax2.boxplot(match_data, patch_artist=True)
# 设置颜色
colors = ['lightblue', 'lightgreen', 'lightpink']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
ax2.set_xticklabels(self.data['比赛'].unique())
ax2.set_ylabel('高速跑动距离 (米)')
ax2.set_title('各比赛高速跑动距离分布')
ax2.grid(axis='y', alpha=0.3)
# 3. 高速跑动距离 vs 总跑动距离(散点图)
ax3 = axes[1, 0]
for player in self.data['球员'].unique()[:5]: # 只显示前5名
player_data = self.data[self.data['球员'] == player]
ax3.scatter(player_data['总跑动距离'], player_data['高速跑动距离'],
label=player, alpha=0.7, s=80)
ax3.set_xlabel('总跑动距离 (米)')
ax3.set_ylabel('高速跑动距离 (米)')
ax3.set_title('高速跑动距离 vs 总跑动距离')
ax3.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
ax3.grid(alpha=0.3)
# 4. 高速跑动占比对比(饼图)
ax4 = axes[1, 1]
avg_ratio = self.data.groupby('球员')['高速跑动占比'].mean()
top_players = avg_ratio.nlargest(5)
colors = plt.cm.Set3(np.linspace(0, 1, 5))
wedges, texts, autotexts = ax4.pie(top_players.values, labels=top_players.index,
autopct='%1.1f%%', colors=colors,
startangle=90)
ax4.set_title('高速跑动占比前5名')
# 5. 冲刺次数对比(折线图)
ax5 = axes[2, 0]
sprint_data = self.data.pivot_table(index='比赛', columns='球员', values='冲刺次数', aggfunc='mean')
sprint_data.plot(ax=ax5, marker='o', linewidth=2, markersize=6)
ax5.set_xlabel('比赛')
ax5.set_ylabel('平均冲刺次数')
ax5.set_title('各球员平均冲刺次数变化')
ax5.grid(alpha=0.3)
ax5.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# 6. 相关性热力图
ax6 = axes[2, 1]
corr_matrix = self.data[['高速跑动距离', '总跑动距离', '冲刺次数', '最高速度', '高速跑动占比']].corr()
im = ax6.imshow(corr_matrix, cmap='RdBu_r', aspect='auto', vmin=-1, vmax=1)
# 添加相关系数标签
for i in range(len(corr_matrix)):
for j in range(len(corr_matrix)):
ax6.text(j, i, f'{corr_matrix.iloc[i, j]:.2f}',
ha='center', va='center', fontsize=8)
ax6.set_xticks(range(len(corr_matrix.columns)))
ax6.set_yticks(range(len(corr_matrix.columns)))
ax6.set_xticklabels(corr_matrix.columns, rotation=45, ha='right')
ax6.set_yticklabels(corr_matrix.columns)
ax6.set_title('指标相关性热力图')
plt.tight_layout()
plt.show()
def statistical_tests(self):
"""统计检验"""
if self.data is None:
print("请先生成或加载数据")
return
print("\n" + "=" * 60)
print("统计检验")
print("=" * 60)
# 1. 方差分析 (ANOVA)
match_groups = [self.data[self.data['比赛'] == m]['高速跑动距离']
for m in self.data['比赛'].unique()]
f_stat, p_value = stats.f_oneway(*match_groups)
print(f"\n1. 单因素方差分析 (ANOVA):")
print(f" F统计量: {f_stat:.4f}")
print(f" p值: {p_value:.6f}")
if p_value < 0.05:
print(" 不同比赛间的高速跑动距离存在显著差异")
else:
print(" 不同比赛间的高速跑动距离无显著差异")
# 2. 正态性检验
all_high_speed = self.data['高速跑动距离']
stat, p_value = stats.normaltest(all_high_speed)
print(f"\n2. 正态性检验 (D'Agostino-Pearson):")
print(f" 统计量: {stat:.4f}")
print(f" p值: {p_value:.6f}")
if p_value < 0.05:
print(" 数据不符合正态分布")
else:
print(" 数据符合正态分布")
# 3. 相关性分析
print(f"\n3. 相关性分析:")
correlation_matrix = self.data[['高速跑动距离', '总跑动距离', '冲刺次数', '最高速度']].corr()
print(correlation_matrix)
def generate_report(self):
"""生成分析报告"""
if self.data is None:
print("请先生成或加载数据")
return
print("\n" + "=" * 60)
print("高速跑动距离分析报告")
print("=" * 60)
# 整体表现
print(f"\n1. 整体表现")
print(f" 平均高速跑动距离: {self.data['高速跑动距离'].mean():.1f} 米")
print(f" 最大高速跑动距离: {self.data['高速跑动距离'].max():.1f} 米")
print(f" 最小高速跑动距离: {self.data['高速跑动距离'].min():.1f} 米")
print(f" 标准差: {self.data['高速跑动距离'].std():.1f} 米")
# 最佳表现球员
best_player = self.data.groupby('球员')['高速跑动距离'].mean().idxmax()
best_distance = self.data.groupby('球员')['高速跑动距离'].mean().max()
print(f"\n2. 最佳表现")
print(f" 最佳球员: {best_player}")
print(f" 平均高速跑动距离: {best_distance:.1f} 米")
# 比赛影响
match_avg = self.data.groupby('比赛')['高速跑动距离'].mean()
print(f"\n3. 比赛影响")
for match, avg_distance in match_avg.items():
print(f" {match}: {avg_distance:.1f} 米")
# 建议
print(f"\n4. 分析建议")
weak_players = self.data.groupby('球员')['高速跑动距离'].mean().nsmallest(3)
print(f" 需要加强训练的球员: {', '.join(weak_players.index)}")
print(f"\n5. 最佳冲刺表现")
sprint_king = self.data.groupby('球员')['冲刺次数'].mean().idxmax()
print(f" 冲刺王: {sprint_king}")
# 主程序
def main():
"""主函数"""
# 创建分析器实例
analyzer = HighSpeedRunningAnalyzer()
# 生成模拟数据
print("生成模拟数据...")
data = analyzer.generate_sample_data(n_players=8, n_matches=3)
# 显示数据预览
print("\n数据预览:")
print(data.head(10))
# 基础统计分析
analyzer.basic_statistics()
# 球员对比
analyzer.player_comparison(top_n=3)
# 统计检验
analyzer.statistical_tests()
# 可视化对比
analyzer.visualize_comparison()
# 生成报告
analyzer.generate_report()
# 导出数据
print("\n正在导出数据...")
data.to_csv('high_speed_running_analysis.csv', index=False, encoding='utf-8-sig')
print("数据已导出到 high_speed_running_analysis.csv")
if __name__ == "__main__":
main()
这个案例的主要功能包括:
📊 核心功能
-
数据生成与加载
- 自动生成模拟的高维跑动数据
- 支持加载真实CSV数据
-
统计分析
- 基础统计指标计算
- 方差分析(ANOVA)
- 正态性检验
- 相关性分析
-
可视化对比
- 球员间高速跑动距离对比(条形图)
- 各比赛分布对比(箱线图)
- 散点图分析相关性
- 占比饼图
- 趋势分析折线图
- 相关性热力图
-
报告生成
- 自动生成分析报告
- 识别最佳/需改进球员
- 提供训练建议
🚀 运行示例
python high_speed_analysis.py
输出示例:
生成模拟数据...
数据预览:
球员 比赛 高速跑动距离 总跑动距离 冲刺次数 最高速度 高速跑动占比
0 球员_A 第1轮 223.5 1117.3 6 32.5 20.01
1 球员_A 第2轮 218.9 1094.7 5 31.8 20.00
...
基础统计分析
...
这个综合案例展示了Python在体育数据分析中的应用,涵盖了数据生成、统计分析、可视化和报告生成的全流程,您可以根据实际需求调整参数或扩展功能。