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
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'
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'])
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)
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.