1

Is possible to pass a DataFrame to an apply function like this?

df2 = df1.apply(func,axis=1,args=df2)
def func(df1,df2):
    # do stuff in df2 for each row of df1
    return df2

The two DataFrames do not have the same length.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Lorenzo Bottaccioli
  • 441
  • 1
  • 7
  • 20

1 Answers1

5

From the df.apply docs:

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)

Applies function along input axis of DataFrame.

args : tuple

Positional arguments to pass to function in addition to the array/series.

The right way is to pass your arguments in a tuple, like this:

df1.apply(func, axis=1, args=(df2, ))

Further improvements to your code would be possible if it were known what you are trying to achieve.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks very much for your answer. That solved a problem I was having. I had a function I wanted to apply to df1 which initially had no arguments, then I changed it to having a single df2 argument. So I went from `df1.apply(func, axis=1)` to `df1.apply(func, axis=1, args=(df2))` but that resulted in a warning about redundant parentheses so I changed it to `df1.apply(func, axis=1, args=df2)` which resulted in the error "The truth value of a DataFrame is ambiguous." So I changed it as you suggested to `df1.apply(func, axis=1, args=(df2, ))` and it is working just as intended. – MarkBC Mar 05 '21 at 22:30
  • Thanks @cs95. I forgot to tag you in the previous comment. – MarkBC Mar 05 '21 at 22:37