Making a custom window type for pandas rolling mea

2019-02-26 14:21发布

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)?

1条回答
Summer. ? 凉城
2楼-- · 2019-02-26 14:59

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')
查看更多
登录 后发表回答