-1

Using the example dataframe below,

How do I iterate over both Grade 1 and Grade 2 columns to select any grade 1 greater than 24 with any Grade 2 greater than 50 using list_comprehension or vectorization mentioned here

import pandas as pd 

data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 
        'Grade 1':[27, 24, 22, 32], 
        'Grade 2':[60, 50, 75, 60],
        'Final Grade':[77, 74, 97, 92]}

df = pd.DataFrame(data)

print(df[['Name', 'Grade 1', 'Grade 2','Final Grade']]) 

Based on those conditions I would like the expected output to return something like:

Jai has Grade 1 score of 27 and Grade 2 score of 60
Anuj has Grade 1 score of 32 and Grade 2 score 60
Gaurav has Grade 1 score of 22 and Grade 2 score of 75

Following a tutorial but trying to go beyond in understanding how to implement either of those concepts.

InlLad
  • 69
  • 10

3 Answers3

1

Do you mean something like this?

res = df[(df['Grade 1'] > 24) & (df['Grade 2'] > 50)]
print(res)

   Name  Grade 1  Grade 2  Final Grade
0   Jai       27       60           77
3  Anuj       32       60           92
Bertil Johannes Ipsen
  • 1,656
  • 1
  • 14
  • 27
1

You can use apply, although, in this case, I do not think it will make too much difference.

df[(df["Grade 1"] > 24) & (df["Grade 2"] > 50)].apply(
    lambda x: f"{x['Name']} has Grade 1 score of {x['Grade 1']} and Grade 2 score of {x['Grade 2']}",
    axis=1,
).tolist()


['Jai has Grade 1 score of 27 and Grade 2 score of 60',
 'Anuj has Grade 1 score of 32 and Grade 2 score of 60']
nocibambi
  • 2,065
  • 1
  • 16
  • 22
1

Your question isn't really clear so I hope you can clarify things a bit. For example, you need Grade 1 which are greater than 24 but in your expected output, you are expecting Gaurav with 22.

However, to make things simpler, I would say never try to iterate in pandas. At the very least, it is a practice that is best left for exception cases.

Here you can use conditional assignments :

df[(df['Grade 1'] > 24) & (df['Grade 2'] > 50 )]]

out :
 Name     Grade 1    Grade 2    Final Grade 
 Jai        27         60           77
Anuj        32         60           92

Edit : If in case you wish to have an output with either Grade 1 > 24 OR Grade 2 > 50, just replace & with '|'