我正试图编写一个函数来遍历两组多列,如下所示,在我的代码中。
但是,我编写的函数只允许我一次遍历每组中的1列。
我正在寻找有关如何更好地编写代码的建议,该代码允许我使用一个函数而不是三个函数遍历两组列。
具体来说,我正在寻求将功能1,2和3合并为一个功能。
否则,任何其他解决方案也将受到赞赏! 我尝试过在线搜索,但没有找到解决我问题的任何类似方法!
#1st set of columns to loop through
col1='revenue'
col2='manpower'
col3='others'
#2nd set of columns to loop through
target1='alt_rev'
target2='alt_man'
target3='alt_oth'
#function 1 to loop through 1 column from each set with con_var as condition
def revised_rev (row):
>>if row['con_var'] == 1 :
return row[col1]
>>>if row['con_var'] != 1 :
return row[target1]
>>>>return None
df['new_rev'] = df.apply (lambda row: revised_rev(row), axis=1)
###function 2 to loop through 1 column from each set with con_var as condition
def revised_man (row):
>>if row['con_var'] == 1 :
return row[col2]
>>>if row['con_var'] != 1 :
return row[target2]
>>>>return None
df['new_man'] = df.apply (lambda row: revised_man(row), axis=1)
#function 3 to loop through 1 column from each set with con_var as condition
def revised_oth (row):
>>if row['con_var'] == 1 :
return row[col3]
>>>if row['con_var'] != 1 :
return row[target3]
>>>>return None
df['new_oth'] = df.apply (lambda row: revised_oth(row), axis=1)
#- my output after running through function1
#see"https://i.imgur.com/tZh9Us0.png" for image