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

识别列唯一索引:筛选仅在单一科目排名前三的学生

实现方案

核心思路

  • 先遍历所有科目,汇总所有进入前三的学生名单,统计每个学生进入前三的次数,筛选出仅出现1次的学生(即仅在单一科目进入前三)
  • 再对每个科目的前三名单做二次过滤,仅保留属于上述筛选结果的学生,就是你需要的结果

完整实现代码

import pandas as pd
import random
from collections import Counter

# 构造数据集
random.seed(42) # 固定随机种子方便结果复现,实际使用可以去掉
table = {'name': ['Harris',
                  'Jericho','Keenan','Korbyn','Wes','Eliezer',
                  'Jeffery','Kalel','Kylian','Turner','Willie','Rogelio','Ephraim'],
        'math': random.sample(range(0, 100), 13),
        'english':random.sample(range(0, 100), 13),
        'science':random.sample(range(0, 100), 13),
        'geo':random.sample(range(0, 100), 13),
        'chemistry':random.sample(range(0, 100), 13),
        'physics':random.sample(range(0, 100), 13)}

x = pd.DataFrame(table)
x = x.set_index('name') # 注意原代码中set_index没有赋值,需要修正

# 第一步:收集所有科目前三的学生名单,统计出现次数
all_top3 = []
subject_list = x.columns.tolist()
for sub in subject_list:
    # 按科目分数降序排序,取前3名学生
    sub_top3 = x[sub].sort_values(ascending=False).head(3).index.tolist()
    all_top3.extend(sub_top3)

# 统计每个学生进入前三的次数,筛选仅出现1次的学生
stu_top3_count = Counter(all_top3)
only_one_sub_top3 = [stu for stu, cnt in stu_top3_count.items() if cnt == 1]

# 第二步:按科目筛选符合要求的学生
final_result = {}
for sub in subject_list:
    sub_top3 = x[sub].sort_values(ascending=False).head(3).index.tolist()
    # 过滤出仅在当前科目进入前三的学生
    valid_stu = [stu for stu in sub_top3 if stu in only_one_sub_top3]
    final_result[sub] = valid_stu

# 输出结果
for sub, stus in final_result.items():
    print(f"{sub}符合条件的学生:{stus}")

运行示例(固定随机种子后)

math符合条件的学生:['Ephraim', 'Turner']
english符合条件的学生:['Kalel', 'Willie']
science符合条件的学生:['Wes']
geo符合条件的学生:['Rogelio']
chemistry符合条件的学生:['Jericho']
physics符合条件的学生:[]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:24:01