2
    import pandas as pd
    d = {'a': [1,2,3],
         'b': [3,4,5],
         'c': [5,4,3]}
    df=pd.DataFrame(d)
    df

returns:

        a   b   c
    0   1   3   5
    1   2   4   4
    2   3   5   3

I create the following function to calculate m:

    def foo(x,y,z):
        m=x(y+z)
        return m

Then apply it to df:

    df['new']=df[['a', 'b', 'c']].apply(lambda x,y,z: foo(x,y,z))

but this gives following error:

    ("<lambda>() missing 2 required positional arguments: 'y' and 'z'", 'occurred at index a')

How can i solve it?

Alex44
  • 3,597
  • 7
  • 39
  • 56
williamscathy825
  • 185
  • 1
  • 1
  • 11

1 Answers1

1

You have 2 problems, 1 is a syntax error where you seem to forget the * operator:

m=x(y+z)

should be:

m=x*(y+z)

The more important one is about how you are distributing the arguments into the foo function via lambda. You can fix it with this solution:

df['new']=df.apply(lambda x: foo(x['a'],x['b'],x['c']),axis=1)

see also Applying function with multiple arguments to create a new pandas column

aviya.developer
  • 3,343
  • 2
  • 15
  • 41
Raphael
  • 810
  • 6
  • 18
  • 1
    Thank you all! fixed the x*(y+z) like Tadhg McDonald-Jensen said and applied df['new']=df.apply(lambda x: foo(x['a'],x['b'],x['c']),axis=1) like Raphael suggested and it all works now ^-^ seems i can't select both answers as correct :( – williamscathy825 Feb 16 '20 at 22:41