updated comment
@unutbu wrote a great answer to a very similar question here , but it seems his answer is based on pd.rolling_apply , which passes the index of the function. I'm not sure how to replicate this using the current DataFrame.rolling.apply method.
original answer
It looks like the variable passed to the argument through the apply function is an array with the number of each column (one at a time), not a DataFrame, so you don't have access to any other columns, unfortunately.
But you can use some logic to temporarily create a new column based on whether var2 74 or not, and then use the crop method.
df['new_var'] = df.var2.eq(74).mul(df.var1).rolling(2, min_periods=1).sum() var1 var2 new_var 0 43 74 43.0 1 44 74 87.0 2 45 66 44.0 3 46 268 0.0 4 47 66 0.0
The time column is based on the first half of the code above.
df.var2.eq(74).mul(df.var1)
Search for the type of variable passed for use
It is very important to know what is actually passed to the apply function, and I canβt always remember what is passed, so if I'm not sure, I will print the variable along with its type so that it is clear to me what kind of object I'm dealing with. See this example with the original DataFrame.
def foo(x): print(x) print(type(x)) return x.sum() df.rolling(2, min_periods=1).apply(foo)
Output
[ 43.] <class 'numpy.ndarray'> [ 43. 44.] <class 'numpy.ndarray'> [ 44. 45.] <class 'numpy.ndarray'> [ 45. 46.] <class 'numpy.ndarray'> [ 46. 47.] <class 'numpy.ndarray'> [ 74.] <class 'numpy.ndarray'> [ 74. 74.] <class 'numpy.ndarray'> [ 74. 66.] <class 'numpy.ndarray'> [ 66. 268.] <class 'numpy.ndarray'> [ 268. 66.] <class 'numpy.ndarray'>
source share