我有一个如下的数据框。
我检查score1、2、3列并打印相应的科目。我可以比较两列并打印相应的文本。
我如何包含另一列?
import pandas as pd
import numpy as np
raw_data = {'Sub1':['A','B','C','D','E'],
'Sub2':['F','G','H','I','J'],
'Sub3':['K','L','M','N','O'],
'S_score1': [1, 0, 0, 6,0],
'F_score1' : [0, 1,0,0,0],
'L_score1' : [1,2,3,0,4],
'S_score2': [0, 0, 0, 6,0],
'F_score2' : [0, 1,0,0,0],
'L_score2' : [1,2,3,0,4],
'S_score3': [0, 0, 0, 6,0],
'F_score3' : [0, 1,0,0,0],
'L_score3' : [1,2,3,0,4]}
df2 = pd.DataFrame(raw_data, columns = ['Sub1','Sub2','Sub3','S_score1', 'F_score1','L_score1','S_score2', 'F_score2','L_score2','S_score3', 'F_score3','L_score3'])
def S_text(f):
s_text = "You have scored on {}" .format(f['Sub1']) if f['S_score1'] >= 1 else "You have scored on {}" .format(f['Sub2'])
return s_text
def F_text(f):
f_text = "You have scored on {}" .format(f['Sub1']) if f['F_score1'] >= 1 else "You have scored on {}" .format(f['Sub2'])
return f_text
def L_text(f):
l_text = "You have scored on {}" .format(f['Sub1']) if f['L_score1'] >= 1 else "You have scored on {}" .format(f['Sub2'])
return l_text
df2['s_text'] = df2.apply(S_text, axis=1)
df2['f_text'] = df2.apply(F_text, axis=1)
df2['l_text'] = df2.apply(L_text, axis=1)
我想进行如下类型的比较,但是出现了错误。基本上,如果两列满足条件(scores>=1),我想打印出这两个学科。如果三列满足条件(scores>=1),我想以以下文本形式打印出这三个学科。有没有其他方法来比较三列并打印文本?
def S_text(f):
s_text = "You have scored on {}" .format(f['Sub1']) if f['S_score1'] >= 1
elif f['S_score2'] >= 1 "You have scored on {}" .format(f['Sub2'])
elif f['S_score3'] >=1 "You have scored on {}" .format(f['Sub3'])
elif f['S_score1'] >=1 and f['S_score2']>=1 "You have scored on {} {}" .format(f['Sub1'], f['Sub2'])
elif f['S_score1'] >=1 and f['S_score3']>=1 "You have scored on {} {}" .format(f['Sub1'], f['Sub3'])
elif f['S_score2'] >=1 and f['S_score3']>=1 "You have scored on {} {}" .format(f['Sub2'], f['Sub3'])
elif f['S_score1'] >=1 and f['S_score2']>=1 and f['S_score3']>=1 "You have scored on {} {} {}" .format(f['Sub1'],f['Sub2'], f['Sub3'])
return s_text
期望输出: