How to calculate moving average with custom weights in pandas?

The Pandas documentation http://pandas.pydata.org/pandas-docs/stable/computation.html provides an example of calculating moving averages:

ser = pd.Series(np.random.randn(10), index=pd.date_range('1/1/2000', periods=10))
pd.rolling_window(ser, 5, 'boxcar')

The second line calculates a moving average with a window of 5 and equal weights for each of the five observations. The documents are painfully related to the possibility of using custom weights ("When passing win_type, instead of explicitly specifying weights ..."), but how do you do this?

Thank!

+1
source share
1 answer

I am not a math expert, but stahlous will explain what you need here .

I try to check it out:

import pandas as pd

ser = pd.Series([1,1,1], index=pd.date_range('1/1/2000', periods=3))
print ser

rm1 = pd.rolling_window(ser, window=[2,2,2], mean=False)
rm2 = pd.rolling_window(ser, window=[2,2,2]) #, mean=True

print rm1
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     6
#Freq: D, dtype: float64
print rm2
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     1
#Freq: D, dtype: float64

I window ndarray ([2,2,2]) (rm1) (rm2).

pandas.rolling_window:

: int ndarray:
. , win_type

: boolean, True
True ,

+1

Source: https://habr.com/ru/post/1665391/


All Articles