teteh May
teteh May

Reputation: 455

Python Function Application to Multiple Series

I have a function (hypothetical):

def example_fct(x,y)
    return x*y

I want to apply this function into a hypothetical dataframe:

df = 
   number1   number2
0    20        30
1    25        10

Where it will result as:

   number1   number2   multiply
0    20        30        600
1    25        10        250

I tried to use apply:

df_['multiply'] = example_fct(df.number1,df.number2)

But this does not work as the function arguments are scalar instead of series. I can always use .apply for a function that has single input argument, but this function uses 2 input arguments.

Furthermore, I am also wondering if this function can be used with series from different data frames (but both data frames have the same length).

Upvotes: 0

Views: 50

Answers (1)

bigbounty
bigbounty

Reputation: 17368

In [81]: df
Out[81]:
   number1  number2
0       20       30
1       25       10

In [82]: def example_fct(x,y):
    ...:     return x*y
    ...:

In [83]: df["multiply"] = df.apply(lambda x:example_fct(x["number1"], x["number2"]), axis=1)

In [84]: df
Out[84]:
   number1  number2  multiply
0       20       30       600
1       25       10       250

Upvotes: 2

Related Questions