According to pandas documentation on rolling
Size of the moving window. This is the number of observations used for calculating the statistic. Each window will be a fixed size.
Therefore, maybe you need to fake a rolling operation with various window sizes like this
test_df = pd.DataFrame({'x':np.linspace(1,10,10),'y':np.linspace(1,10,10)})
test_df['win_locs'] = np.linspace(1,10,10).astype('object')
for ind in range(10): test_df.at[ind,'win_locs'] = np.random.randint(0,10,np.random.randint(5)).tolist()
# rolling operation with various window sizes
def worker(idx_list):
x_slice = test_df.loc[idx_list,'x']
return np.sum(x_slice)
test_df['rolling'] = test_df['win_locs'].apply(worker)
As you can see, test_df is
x y win_locs rolling
0 1.0 1.0 [5, 2] 9.0
1 2.0 2.0 [4, 8, 7, 1] 24.0
2 3.0 3.0 [] 0.0
3 4.0 4.0 [9] 10.0
4 5.0 5.0 [6, 2, 9] 20.0
5 6.0 6.0 [] 0.0
6 7.0 7.0 [5, 7, 9] 24.0
7 8.0 8.0 [] 0.0
8 9.0 9.0 [] 0.0
9 10.0 10.0 [9, 4, 7, 1] 25.0
where the rolling operation is achieved with apply method.
However, this approach is significantly slower than the native rolling, for example,
test_df = pd.DataFrame({'x':np.linspace(1,10,10),'y':np.linspace(1,10,10)})
test_df['win_locs'] = np.linspace(1,10,10).astype('object')
for ind in range(10): test_df.at[ind,'win_locs'] = np.arange(ind-1,ind+1).tolist() if ind >= 1 else []
using the approach above
%%timeit
# rolling operation with various window sizes
def worker(idx_list):
x_slice = test_df.loc[idx_list,'x']
return np.sum(x_slice)
test_df['rolling_apply'] = test_df['win_locs'].apply(worker)
the result is
41.4 ms ± 4.44 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
while using native rolling is ~x50 faster
%%timeit
test_df['rolling_native'] = test_df['x'].rolling(window=2).sum()
863 µs ± 118 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)