Home > Mobile >  Getting the maximum value from filtered values in pandas DataFrames? - Python, Pandas
Getting the maximum value from filtered values in pandas DataFrames? - Python, Pandas

Time:12-28

I want to Filter the days to Monday and get the maximum OverallGrade got on Mondays. Alternatively I have made a new Data frame for it and it shows the intended answer 90, but is there a way to do this without creating a new Data Frame?

When seeing the end result i need to see the student id also as shown in the alt solution! Also I do not want to use days as the index and reset the index again for this purpose! ( I actually have the days as dates and do not want to use them as the index, just converted to Day names here for simplicity)

import pandas as pd

ClassData = {
  "Days":         ["Monday","Wednesday","Monday","Friday","Tuesday","Monday","Friday"],
  "OverallMarks": [   150,     140,       180,      250,      200 ,    240,     170  ],
  "OverallGrade": [    70,      60,        90,      110,       85 ,     80,      71  ],
  "StudentID" :   ['a','b', 'c', 'd', 'e', 'f', 'g']
}

MyDataFrame1 = pd.DataFrame(ClassData)

# Alternate Solution I use - Creating a new Dataframe for only the mondays
NewDataFrame = MyDataFrame1[ MyDataFrame1['Days'] == "Monday" ] # Gets all Mondays
print( NewDataFrame[ NewDataFrame['OverallGrade'] == int(NewDataFrame['OverallGrade'].max()) ][['StudentID','OverallGrade']] ) 
# Gets max grade as 90 and shows the student id and grade

CodePudding user response:

  • First select on "Monday", just like you did
  • Then sort it descending, based on the 'OverallGrade'
  • Select the first element
print( MyDataFrame1[ MyDataFrame1['Days'] == "Monday" ].sort_values(by='OverallGrade', ascending=False).iloc[0])
  • Related