如何使用Python计算多场景多轮运行结果的平均分?
用Python计算不同场景运行结果的平均分
下面提供两种实用方法,根据你的需求选择:
方法一:使用Pandas(推荐,适合结构化表格)
Pandas是处理表格数据的利器,操作简单高效:
- 先安装依赖(如果没装过):
pip install pandas
- 核心代码:
import pandas as pd # 读取表格文件,CSV格式用read_csv,Excel用read_excel df = pd.read_csv("your_table.csv") # 或者 df = pd.read_excel("your_table.xlsx") # 计算各场景(列)的平均分,只处理数值列 scene_means = df.mean(numeric_only=True) # 打印结果 print("各场景平均分:") print(scene_means)
- 说明:如果你的表格里有非数值列,
numeric_only=True会自动忽略,避免计算出错;输出结果会以场景名为索引,对应显示平均分。
方法二:基础Python实现(无需第三方库)
如果不想安装额外库,用内置模块就能搞定:
import csv # 初始化存储各场景数据的字典 scene_data = {} with open("your_table.csv", "r", encoding="utf-8") as file: reader = csv.DictReader(file) # 初始化每个场景的空列表 for col in reader.fieldnames: scene_data[col] = [] # 逐行读取数据并存入对应场景 for row in reader: for scene, value in row.items(): try: # 转换为浮点型,确保是数值 scene_data[scene].append(float(value)) except ValueError: # 跳过非数值内容,比如表头或异常值 continue # 计算平均分 scene_means = {} for scene, values in scene_data.items(): if values: # 避免空列表报错 scene_means[scene] = sum(values) / len(values) # 格式化输出结果 print("各场景平均分:") for scene, mean in scene_means.items(): print(f"{scene}: {mean:.2f}")
- 说明:这段代码兼容CSV格式的表格,会自动识别表头作为场景名,跳过无法转换为数值的内容,最后输出保留两位小数的平均分。
内容的提问来源于stack exchange,提问作者user2077648
相关产品推荐
相关产品推荐

