Making a custom window type for pandas rolling mean
Asked Answered
P

1

3

I understand rolling allows you to specify the window type used for calculating the rolling mean. The docs list a variety of windows type options available here. However, I am trying to use a symmetrically weighted window type of length 4 whose definition is like (and is not available as built-in):

(a + 2*b + 2*c + d)/6

where a,b,c and d are the four elements of the rolling window at any given time and [1/6, 2/6, 2/6, 1/6] would be the associated weights.

If I go by the default window type (boxcar), I get this:

import pandas as pd
rs = pd.Series(range(10))
print rs.rolling(4, win_type = 'boxcar').mean()

0    NaN
1    NaN
2    NaN
3    1.5
4    2.5
5    3.5
6    4.5
7    5.5
8    6.5
9    7.5
dtype: float64

Any idea how I could go about using a custom defined rolling window type (a symmetrically weighted moving average, in this case)?

Punnet answered 19/1, 2018 at 15:50 Comment(1)
Another was to do it: https://mcmap.net/q/462021/-rolling-difference-in-pandasScribe
S
6

Create a kernel like this:

import numpy as np
kernel = np.array([1,2,2,1])/6

then convolve with your series:

np.convolve(rs,kernel,'same')
Scribe answered 19/1, 2018 at 16:42 Comment(1)
Thank you! Learnt something new.Punnet

© 2022 - 2024 — McMap. All rights reserved.