Python pandas,与作为数据帧行条目的args一起应用

Python pandas,与作为数据帧行条目的args一起应用,python,pandas,apply,args,Python,Pandas,Apply,Args,我有一个数据帧'df'和两列'a'和'B',我有一个函数和两个参数 def myfunction(B, A): # do something here to get the result return result 我想使用“apply”函数将它逐行应用于df df['C'] = df['B'].apply(myfunction, args=(df['A'],)) 但是我得到了错误 ValueError: The truth value of a Series is ambi

我有一个数据帧'df'和两列'a'和'B',我有一个函数和两个参数

def myfunction(B, A):
    # do something here to get the result
    return result
我想使用“apply”函数将它逐行应用于df

df['C'] = df['B'].apply(myfunction, args=(df['A'],))
但是我得到了错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
这里发生了什么,它似乎把df['A']作为整个系列!不只是需要该系列中的行条目。

我认为您需要:

import pandas as pd
df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6]})

print (df)
   A  B
0  1  4
1  2  5
2  3  6

def myfunction(B, A):
    #some staff  
    result = B + A 
    # do something here to get the result
    return result

df['C'] = df.apply(lambda x: myfunction(x.B, x.A), axis=1)
print (df)
   A  B  C
0  1  4  5
1  2  5  7
2  3  6  9
或:


为什么我不能对apply函数使用'args'参数?@RunnerBean您可以很好地传递参数
apply
接受
kwargs
这样您就可以像这样传递参数:
df['B'].apply(myfunction,A=df['A'])
但是在这种情况下,这是一个坏主意,因为您会将整个序列传递给应用于每一行的函数。
def myfunction(x):

    result = x.B + x.A
    # do something here to get the result
    return result

df['C'] = df.apply(myfunction, axis=1)
print (df)
   A  B  C
0  1  4  5
1  2  5  7
2  3  6  9