简体   繁体   中英

Passing a vector into the window argument of Pandas rolling_mean()

I would like to calculate the rolling mean of a time series but using a list of different window sizes.

Indeed, I can use a for loop to achieve this like so:

def rolling_mean(series, *vals):
    for i in vals:
        m = pd.rolling_mean(series, window=i)
        print (m)

However I would like to instead try and find a vectorized method which would utilize Pandas' functionality better. Initially I would have imagined something like this would have been perfect:

def rolling_mean(series, *vals):
    df = pd.rolling_mean(series, window=vals)
    print (df)

where the above method would return a DataFrame object of rolling means of varying window lengths of the series argument. Unfortunately the rolling_mean() window argument only accepts integers. I cannot think of any other way to achieve this.

Is there a vectorized way to pass the *vals values into rolling_mean()?

Say for example you want to calculate the rolling mean over windows = [20, 40, 60, 80, 120, 250]

#create a new dataframe
rolling_means = pd.DataFrame()

windows = [20, 40, 60, 80, 120, 250]
labels = ['20', '40', '60', '80', '120', '250']

for window,label in zip(windows, labels):
    rolling_means[label] = pd.rolling_mean(series, window = window)

This will create a dataframe with each column being the different rolling mean.

all you would need to do to trim the data so that is has full data points for comparison is:

rolling_means.dropna(how = 'any', inplace=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM