NumPy - 最高平均值的索引

3

我有以下数值:

grade_list = [[99 73 97 98] [98 71 70 99]]
student_ids = [521 597 624 100]

grade_list中的每个数组都代表每个学生的成绩列表(第521位学生的成绩是99,98;第597位学生的成绩是73,71,以此类推...)

我的目标是返回平均分最高的学生的ID(应该是521,因为平均分为98.5,是最高的)

我尝试了这个:

def find_student_with_max_avg(grade_list, student_ids):
    mean_grades = np.mean(grade_list, axis=1)
    best_student_index = student_ids[mean_grades.argmax()]
    return best_student_index

返回了521,但我尝试更改grade_list,即使将该学生的成绩设置为0,它仍然返回521

不确定如何获得最优秀学生的学生ID,有什么想法吗?

3个回答

2

试一下这个:

import numpy as np

grade_list = [[99,73,97,98] ,[98,71,70,99]]
student_ids = [521,597,624,100]

# axis 0 is row-wise, and 1 is column-wise
student_ids[np.array(grade_list).mean(axis=0).argmax()]

1
您正在沿着错误的轴线进行平均值计算:
>>> np.mean(grade_list, axis=1)
array([91.75, 84.5 ])

改变轴并检查您获得的平均值是否与学生ID数量相同。
>>> np.mean(grade_list, axis=0)
array([98.5, 72. , 83.5, 98.5])

0
我会使用 Counter 来完成这个任务。
from collections import Counter
import numpy as np


grade_list = [[99, 73, 97, 98], [98, 71, 70, 99]] 
student_ids = [521, 597, 624, 100]                                     

c = Counter() 
for i,n in enumerate(student_ids): 
    c.update({n:np.mean([item[i] for item in grade_list])}) 
                                                                   

c.most_common()                                                        
[(521, 98.5), (100, 98.5), (624, 83.5), (597, 72.0)]

正如您所看到的,在这种情况下,您得到了2名最优秀的学生。

In [17]: best_score = c.most_common(1)[0][1]                                    

In [18]: best_score                                                             
Out[18]: 98.5

In [19]: best_students = [k for k,v in c.items() if v == best_score]            

In [20]: best_students                                                          
Out[20]: [521, 100]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接