0

How to apply a function with multiple arguments to a dataframe? My function is something like this:

def test(a,b,c,d,e,f):
    if b == 1 :
        if d == 0 :
            return a-f
    if b == 0 :
        if c == 1 :
            return a-e

My sample data is this :

a b c d e f
2021-04-29 22:04:000 1 0.0 0.0 2021-04-28 10:10:00 2021-04-29 23:14:00
2021-06-10 06:00:00 0 1.0 1.0 2021-06-09 23:00:00 2021-06-11 00:29:00
2021-06-09 23:00:00 1 0.0 0.0 2021-06-06 11:00:00 2021-06-10 06:00:00
2021-06-06 11:00:00 0 1.0 1.0 2021-06-06 08:00:00 2021-06-09 23:00:00
2021-06-06 08:00:00 1 0.0 0.0 2021-06-06 04:00:00 2021-06-06 11:00:00

I tried this line of code and then shows error : the code:

df['dt'] = df.apply(test, args=('a','b','c','d','e','f'), axis=1)

the error:

test() takes 6 positional arguments but 7 were given

I don't understand why it detected as 7 arguments when in my code only six.

1
  • The first argument is always populated with row, any values passed as args are additional. In this case you've passed the literal characters a-f as additional arguments. Commented Jun 26, 2021 at 23:26

1 Answer 1

1

You could try changing your function like so:

def test(row):
    a,b,c,d,e,f = row
    if b == 1 :
        if d == 0 :
            return a-f
    if b == 0 :
        if c == 1 :
            return a-e

Then modify the way you apply the function like so:

df['dt'] = df.apply(test, axis=1)
Sign up to request clarification or add additional context in comments.

4 Comments

How to apply if the column is not in the same order, have different name, or have other columns between the arguments?
the names of the columns make no difference since test() is unpacking each row into 6 variables. The value of row a will go into variable a, the value of row b will go into variable b, and so on. @RidwanNurzeha
so in other words, I must match the order and number of columns between the function and dataframe?
I just realized I said the wrong thing, I mean to say "The value of column a will go into variable a, the value of column b, will go into variable b..." etc. But yes, the number of variables you use to unpack the row must match the order and number of columns in the data frame. @RidwanNurzeha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.