You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中重排训练得分dataframe并计算均值、绘制折线图的方法

实现步骤(Python方案)

1. 依赖安装

需要用到3个工具库,执行以下命令安装:
pip install pandas openpyxl matplotlib

  • pandas:负责数据格式转换、统计计算
  • openpyxl:负责读取Excel文件
  • matplotlib:负责绘制折线图

2. 数据读取与宽表转长表

import pandas as pd
import matplotlib.pyplot as plt

# 替换为你本地的Excel文件路径
df = pd.read_excel("你的训练数据文件.xlsx")

# 把宽格式列转为长格式行
df_long = df.melt(id_vars=["ID"], var_name="original_col", value_name="score")

# 从原列名拆分出训练类型、周数两个维度
df_long["training type"] = df_long["original_col"].apply(lambda x: "strength" if "strength" in x else "agility")
df_long["Week"] = df_long["original_col"].apply(lambda x: int(x.split("_week_")[-1]))

3. 按周统计平均得分

直接分组统计就能得到你要求的三列结构DataFrame:

mean_df = df_long.groupby(["Week", "training type"], as_index=False)["score"].mean().rename(columns={"score":"mean score"})

4. 绘制两类训练的趋势折线图

# 拆分两类训练的统计结果
agility_data = mean_df[mean_df["training type"] == "agility"].sort_values("Week")
strength_data = mean_df[mean_df["training type"] == "strength"].sort_values("Week")

# 创建上下排布的两个子图
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(12, 9))

# 绘制敏捷训练趋势图
ax1.plot(agility_data["Week"], agility_data["mean score"], color="#1a73e8", marker="o", linewidth=2)
ax1.set_title("40周敏捷训练平均得分变化趋势", fontsize=14)
ax1.set_xlabel("周数", fontsize=12)
ax1.set_ylabel("平均得分", fontsize=12)
ax1.grid(alpha=0.3)

# 绘制力量训练趋势图
ax2.plot(strength_data["Week"], strength_data["mean score"], color="#ea4335", marker="s", linewidth=2)
ax2.set_title("40周力量训练平均得分变化趋势", fontsize=14)
ax2.set_xlabel("周数", fontsize=12)
ax2.set_ylabel("平均得分", fontsize=12)
ax2.grid(alpha=0.3)

# 调整布局避免重叠
plt.tight_layout()
# 若要保存到本地可以加一行:plt.savefig("训练得分趋势.png", dpi=300)
plt.show()

注意事项

  • 如果你的Excel列名命名规则和示例不一致,调整training type和Week的拆分逻辑即可
  • 代码天然支持40周全量数据处理,只要列名遵循训练类型_score_week_周数的规则,无需额外修改就能直接运行

内容的提问来源于stack exchange,提问作者fireplush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 07:33:00