Skip to content Skip to sidebar Skip to footer

Pandas Rolling Average With A Rolling Mask / Excluding Entries

I have a pandas dataframe with a time index like this import pandas as pd import numpy as np idx = pd.date_range(start='2000',end='2001') df = pd.DataFrame(np.random.normal(size=(

Solution 1:

You can use apply to customize your function:

# select indexes you want to average overavg_idx = [idx for idx in range(60) if idx not in range(8, 13)]

# do rolling computation, calculating average only on the specified indexesdf_avg = df.rolling(60).apply(lambda x: x[avg_idx].mean())

The x DataFrame in apply will always have 60 rows, so you can specify your positional index based on this, knowing that the first entry (0) is t-60.

I am not entirely sure about your exclusion logic, but you can easily modify my solution for your case.

Solution 2:

Unfortunately, not. From pandas source code:

df.rolling(window, min_periods=None, freq=None, center=False, win_type=None, 
           on=None, axis=0, closed=None)

window : int, oroffset
    Size of the moving window. This is the number of observations used for
    calculating the statistic. Eachwindow will be a fixed size.

    If its an offsetthen this will be the timeperiodofeach window. Eachwindow will be a variable sized based on the observations included in
    the time-period.

Post a Comment for "Pandas Rolling Average With A Rolling Mask / Excluding Entries"