Jac*_*ack 5 python apply dataframe pandas
在 Pandas 中有没有办法使用列名作为参数名将函数应用于数据框?例如,我有一个函数和一个数据框。
df = pd.DataFrame({'A':[1,2,3],
'B':[1,2,3],
'C':[1,2,3],
'D':[1,2,3]})
def f(A,B,C):
#Pretend code is more complicated
return A + B + C
Run Code Online (Sandbox Code Playgroud)
有没有办法我可以做类似的事情
df.apply(f)
Run Code Online (Sandbox Code Playgroud)
并让熊猫将列与命名参数匹配?
我知道我可以重写函数以获取一行而不是命名参数,但请记住 f 只是一个玩具示例,我的实际函数更复杂
编辑:
基于@juanpa.arrivillaga 的答案想出了它:
df[list(f.__code__.co_varnames)].apply((lambda row: f(**row)), axis=1)
要应用的函数f需要接受行/列,具体取决于axis=0,1, ofdf作为参数,而不是列名。您可以为此目的编写一个包装器。
def wrapper(x, A, B, C):
return f(x[A], x[B], x[C])
df.apply(wrapper, axis=1, args=('A','B','C'))
Run Code Online (Sandbox Code Playgroud)
输出:
0 3
1 6
2 9
dtype: int64
Run Code Online (Sandbox Code Playgroud)
在@juanpa.arrivilillaga 答案的基础上弄清楚了。
df[list(f.__code__.co_varnames)].apply((lambda row: f(**row)), axis=1)