germany
germany

Reputation: 59

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?

Upvotes: 0

Views: 439

Answers (2)

Corralien
Corralien

Reputation: 120391

Fixed code:

def func1(x,y,z):
    a=x*y*z
    print(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.values:  # <- iterate over values
    a = func1(*row)  # <- positional arguments
    df2 = pd.DataFrame(a, index=[0], columns=['a'])
    df2.to_excel(f"Data{counter}.xlsx")  # <- concatenate int and str raise an error
    counter = counter +1

Upvotes: 0

Ade_1
Ade_1

Reputation: 1486

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')

Upvotes: 1

Related Questions