我正在尝试编写一个函数来循环2组多列,如下代码所示。你知道吗
但是,我编写的函数只允许一次循环一列。你知道吗
我正在寻找如何更好地编写代码的建议,该代码允许我使用一个函数而不是三个函数来循环遍历两组列。你知道吗
具体来说,如果可能的话,我希望将函数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
目前没有回答
相关问题 更多 >
编程相关推荐