网站首页 > 技术文章 正文
1.考试成绩表格如图
2.代码实现如下:
import pandas as pd
# 读取原始 Excel 文件
input_file = '期末教学质量评价.xlsx'
output_file = '总分段人数.xlsx'
# 读取 Excel 文件
df = pd.read_excel(input_file)
# 定义排名段
rank_ranges = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300]
# 按总分降序排序全校数据
df_sorted = df.sort_values(by='总分', ascending=False)
# 初始化一个空的 DataFrame 用于存储统计结果
result_df = pd.DataFrame(columns=['班级', '前10', '前20', '前30', '前40', '前50', '前60', '前70', '前80', '前90', '前100', '前200', '前300'])
# 遍历每个班级
for class_name in df['班级'].unique():
# 筛选当前班级的数据
class_df = df_sorted[df_sorted['班级'] == class_name]
# 统计各排名段的人数
counts = []
for rank in rank_ranges:
# 获取全校前 N 名的数据
top_n = df_sorted.head(rank)
# 统计当前班级在全校前 N 名中的人数
count = top_n[top_n['班级'] == class_name].shape[0]
counts.append(count)
# 将统计结果添加到 DataFrame 中
new_row = pd.DataFrame({
'班级': [class_name],
'前10': [counts[0]],
'前20': [counts[1]],
'前30': [counts[2]],
'前40': [counts[3]],
'前50': [counts[4]],
'前60': [counts[5]],
'前70': [counts[6]],
'前80': [counts[7]],
'前90': [counts[8]],
'前100': [counts[9]],
'前200': [counts[10]],
'前300': [counts[11]]
})
result_df = pd.concat([result_df, new_row], ignore_index=True)
# 计算合计行
total_row = {
'班级': '合计',
'前10': result_df['前10'].sum(),
'前20': result_df['前20'].sum(),
'前30': result_df['前30'].sum(),
'前40': result_df['前40'].sum(),
'前50': result_df['前50'].sum(),
'前60': result_df['前60'].sum(),
'前70': result_df['前70'].sum(),
'前80': result_df['前80'].sum(),
'前90': result_df['前90'].sum(),
'前100': result_df['前100'].sum(),
'前200': result_df['前200'].sum(),
'前300': result_df['前300'].sum()
}
# 将合计行添加到 DataFrame 中
result_df = pd.concat([result_df, pd.DataFrame([total_row])], ignore_index=True)
# 将统计结果写入新的 Excel 文件
result_df.to_excel(output_file, index=False)
print(f"统计结果已保存到 {output_file}")
3.呈现结果如下:
猜你喜欢
- 2025-04-27 Python实现学生成绩分段统计
- 263℃Python短文,Python中的嵌套条件语句(六)
- 262℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 256℃Python实现字符串小写转大写并写入文件
- 255℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 115℃原来2025是完美的平方年,一起探索六种平方的算吧
- 96℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 88℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)