Skip to content Skip to sidebar Skip to footer

Passing Arguments To Rolling_apply

I am in need for passing several arguments to my target function for pd.rolling_apply My target function looks like this: def complexFunction(i,j,k,l,verbosity=False): ...

Solution 1:

According to documentation (that you have linked) , you can use the args keyword to pass the arguments, the first argument would be passed in by the rolling_apply , you can define the rest of the arguments as a tuple and pass it into args keyword argument. Example -

 pd.rolling_apply(df,<window>,complexFunction,args=(j,k,l))

Example/Demo -

In [3]: df = pd.DataFrame([[1,2,3],[4,5,6]],columns = ['A','B','C'])

In [8]: def func(i,j,s):
   ...:     print(i,j,s)
   ...:     print('next')
   ...:     return i
   ...:

In [9]: pd.rolling_apply(df,1,func,args=(1,2))
[ 1.] 12next
[ 4.] 12next
[ 2.] 12next
[ 5.] 12next
[ 3.] 12next
[ 6.] 12next

Solution 2:

I usually make my functions take a row as its single input eg.

  def complexFunction(row,verbosity=False):
    i = row.ij= row.jk= row.k

    return0.0

  pd.rolling_apply(df, complexFunction)

Solution 3:

Here is the way using partial from functools.

from functools import partial

defcomplex_function(data, x, y):
    # some calculationsreturnsum(data) * x * y

my_partial_func = partial(complex_function, x=2, y=5)

ser = pd.Series(np.arange(10))
pd.rolling_apply(ser, window=5, func=my_partial_func)

0    NaN
1    NaN
2    NaN
3    NaN
410051506200725083009350
dtype: float64    

Post a Comment for "Passing Arguments To Rolling_apply"