简体   繁体   中英

passing rows of dataframe as argument to a function in python

I am trying to pass columns of a dataframe as arguments to function in row wise manner but I am ending in an error. I tried to do by loop as my actual dataframe and function requires loop only.

def sum(x, y, z):
     return x + y + z
Input = pd.DataFrame({'A': [1, 2,3], 'B': [10, 20,22],'C':[4,5,6]})
output = pd.DataFrame({'output': [15, 27,31]})

##What I tried, but this tells me it needs more arguments
for a in Input:
    sum(a)

Could anyone help me, as I need to iterate all the rows of dataframe as in argument to a function so in short number of columns of dataframe is equal to number of arguments in functions

Try this

Input.apply(lambda row : sum(row.A, row.B, row.C), axis=1)

axis = 1, mean on column level. can refer at pandas apply It asks for more arguments because it does not know which column you want to do operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM