Home > database >  Find max value of a column based on another in python
Find max value of a column based on another in python

Time:10-23

i have 2d list implementation as follows. It shows no. of times every student topped in exams:-

  list = main_record
  ['student1',1]
  ['student2',1]
  ['student2',2]
  ['student1',5]
  ['student3',3]

i have another list of unique students as follows:-

  list = students_enrolled
  ['student1','student2','student3']

which i want to display student ranking based on their distinctions as follows:-

  list = student_ranking
  ['student1','student3','student2']

What built in functions can be useful. I could not pose proper query on net. In other words i need python equivalent of following queries:-

select max(main_record[1]) where name = student1 >>> result = 5 
select max(main_record[1]) where name = student2 >>> result = 2
select max(main_record[1]) where name = student3 >>> result = 3

  

CodePudding user response:

You define a dict base key of studentX and save the max value for each student key then sort the students_enrolled base max value of each key.

from collections import defaultdict

main_record = [['student1',1], ['student2',1], ['student2',2], ['student1',5], ['student3',3]]
students_enrolled = ['student1','student2','student3']

# defind dict with negative infinity and update with max in each iteration
tmp_dct = defaultdict(lambda: float('-inf'))
for lst in main_record:
    k, v = lst
    tmp_dct[k] = max(tmp_dct[k], v)
print(tmp_dct)

students_enrolled.sort(key = lambda x: tmp_dct[x], reverse=True)
print(students_enrolled)

Output:

# tmp_dct =>
defaultdict(<function <lambda> at 0x7fd81044b1f0>, 
            {'student1': 5, 'student2': 2, 'student3': 3})

# students_enrolled after sorting
['student1', 'student3', 'student2']

CodePudding user response:

If it is a 2D list it should look like this: l = [["student1", 2], ["student2", 3], ["student3", 4]]. To get the highest numeric value from the 2nd column you can use a loop like this:

numbers = []
for student in list:
    numbers.append(student[1])

for num in numbers:
    n = numbers.copy()
    n.sort()
    n.reverse()
    student_index = numbers.index(n[0])
    print(list[student_index], n[0])
    numbers.remove(n[0])
  • Related