-2

I'm new to python coding and I do have the below simple list in my code.

Marks = [82,70,60,50,40,30]

Now my requirement is I want to get another column in my output called Result as below

enter image description here

So how to use if and else to achieve the output which i'm looking like

if Marks > 80 print 'Distinction'
if Marks >60 and Marks <= 70 print 'Grade A'
if Marks >50 and Marks <= 60 print 'Grade B'
if Marks >40 and Marks <= 50 print 'Grade C'
else print 'Good for Nothing'
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Vikas
  • 199
  • 1
  • 7
  • See if this helps, https://stackoverflow.com/a/16992783/4985099 – sushanth Aug 06 '20 at 02:49
  • @Sushanth Couldn't get that from the link you provided. – Vikas Aug 06 '20 at 03:03
  • Change your title to the problem you are facing. – mime Aug 06 '20 at 03:52
  • 2
    Why **if-else**? You can use [`pd.cut`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html) try this `pd.cut(df['Marks'], [0,40, 50, 60, 70, 100],labels=['Good for nothing', 'C', 'B', 'A', 'Distinction'])` – Ch3steR Aug 06 '20 at 03:54

3 Answers3

3

this is a good task for np.where:

df['Result'] = 'Good for Nothing'
df['Result'] = np.where((df['Marks'] > 80), 'Distinction', df['Result'])
df['Result'] = np.where((df['Marks'] > 60) & (df['Marks'] <= 70), 'Grade A', df['Result'])
df['Result'] = np.where((df['Marks'] > 50) & (df['Marks'] <= 60), 'Grade B', df['Result'])
df['Result'] = np.where((df['Marks'] > 40) & (df['Marks'] <= 50), 'Grade C', df['Result'])
David Erickson
  • 16,433
  • 2
  • 19
  • 35
  • can this be achieved with if else statement? – Vikas Aug 06 '20 at 03:02
  • `np.select` and `np.where` will be similar performance-wise. @Vikas there is no optimal way in pandas to use the words `if` or `else` in a situation like this. `np.where` is similar to an excel if, then statement. – David Erickson Aug 06 '20 at 03:16
1
Marks = [82,70,60,50,40,30]
df = pd.DataFrame({'Marks' : Marks})
print(df)

def a(b):
if b['Marks'] > 80:
    return 'Distinction'
elif b['Marks'] > 69:
    return 'Grade A'
elif b['Marks'] > 59:
    return 'Grade B'
elif b['Marks'] > 49:
    return 'Grade C'
else:
    return 'Good for Nothing'

df['Result'] = df.apply(a, axis=1)
print(df)
BALAJI R
  • 129
  • 1
  • 9
0

Try something like this in Python3

Marks = [82,70,60,50,40,30]

for i in Marks: 
    if i > 80:
        print('Distinction')
    elif i >60 and i <= 70:
        print('Grade A')
    elif i >50 and i <= 60:
        print('Grade B')
    elif i >40 and i <= 50:
        print('Grade C')
    else:
        print('Good for Nothing')
Josh Kautz
  • 459
  • 3
  • 5
  • 31
  • thanks for that. How do i get the both the columns **Marks** and **Result** from the above output which i'm expecting? – Vikas Aug 06 '20 at 03:17
  • This is a great answer for how to print out the results in the terminal Josh, but I think the OP needs to get this in a dataframe. – David Erickson Aug 06 '20 at 03:24