Selecting minimum value between columns python

Viewed 66

I have a DataFrame that looks like the below. "Name" represents a student name and values below each of the Test variables represent the test grade.

Name Test1 Test2 Test3
Ana  87    93    82
Cole 62    73    84
Sia  64    58    60
Max  93    95    99
Leah 93    90    85
Cam  76    80    83

The desired result is the DataFrame below. Where "MinTestGrade" represents that lowest grade each student earned between the 3. "TestNumber" is the Test they got the lowest grade on.

Name TestNumber MinTestGrade
Ana  3          82
Cole 1          62
Sia  2          58
Max  1          93
Leah 3          85
Cam  1          76

How can I do this using python?

2 Answers

You can pass idxmin and min to agg on axis to find the minimum grade and the column name, i.e. TestNumber, that it corresponds to for each student. Then join the outcome with "Name", rename the columns and finally strip the word "Test" from "TestNumber":

out = df[['Name']].join(df.filter(like='Test').agg(['idxmin', 'min'], axis=1)).rename(columns={'idxmin':'TestNumber', 'min':'MinTestGrade'})
out['TestNumber'] = out['TestNumber'].str.lstrip('Test').astype(int)

Output:

   Name  TestNumber MinTestGrade
0   Ana           3           82
1  Cole           1           62
2   Sia           2           58
3   Max           1           93
4  Leah           3           85
5   Cam           1           76
df.set_index("Name").agg(["idxmin", "min"], axis=1).reset_index()
#    Name idxmin  min
# 0   Ana  Test3   82
# 1  Cole  Test1   62
# 2   Sia  Test2   58
# 3   Max  Test1   93
# 4  Leah  Test3   85
# 5   Cam  Test1   76
Related