我是python编码的新手,我的代码中确实包含以下简单的 list 。
Marks = [82,70,60,50,40,30]
现在我的要求是,我想在输出中获得另一列,称为结果,如下所示
那么如何使用 if 和 else 来实现我想要的输出
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'
答案 0 :(得分:2)
这对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'])
答案 1 :(得分:0)
在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')
答案 2 :(得分:0)
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)