Search code examples
pythonpandaspass-by-reference

How to call positional arguments for a function from a dataframe?


I'm trying to run a function that I've created using a large number of different variations of the input variables. Preferably, I would be able to read in an excel file as a dataframe, with each row having say 3 call arguments across the columns, and the function then executes in a for loop calling on each argument per row. My code currently looks as follows:

def func1(x,y,z):
    a=x*y*z
    return a

data = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
df = pd.DataFrame(data, index=[0, 1, 2], columns=['a', 'b', 'c'])

counter = 1
for row in df:
    a = func1(row)
    df2 = pd.DataFrame(a, index=[0], columns=['a'])
    df2.to_excel("Data" + counter + '.xlsx')
    counter = counter +1

This however yields the error message "func1() missing 2 required positional arguments: 'y' and 'z'". How do I effectively use the column values as call arguments?


Solution

  • Try this then modify to suit your task

    def test(x):
        a= x['a']*  x['b']*  x['c']
        return a
    df.apply(test, axis= 1)
    
    #option2 
    
    df.apply(lambda x: x['a']*  x['b']*  x['c'] ,axis= 'columns')