Is there a way in pandas to apply a function to a dataframe using the column names as argument names? For example, I have a function and a dataframe.
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
Is there a way I can do something like
df.apply(f)
and have pandas match the columns to named arguments?
I know I can rewrite the function to take a row instead of named arguments, but keep in mind that f is just a toy example and my real function is more complicated
EDIT:
Figured it out based @juanpa.arrivillaga answer:
df[list(f.__code__.co_varnames)].apply((lambda row: f(**row)), axis=1)
applyis acting column-wise. In that case it's far more logical to just pass it the Series as you have it. You could make it row-wise but honestly in most cases you can avoid looping with apply in favor of vectorized operations.