Pandas custom window tooltip

Is there a way to customize the roll_mean function window?

data 1 2 3 4 5 6 7 8 

Suppose the window is set to 2, that is, to calculate the average of two data points before and after saving, including observation. Say the third observation. In this case, we will have (1+2+3+4+5)/5 = 3 . So, etc.

+6
source share
1 answer

Calculate the usual moving average using the direct (or reverse) window, and then use the shift method to re-center, as you wish.

 data_mean = pd.rolling_mean(data, window=5).shift(-2) 

If you want to average more than two data points before and after observation (a total of 5 data points), do window=5 .

For instance,

 import pandas as pd data = pd.Series(range(1, 9)) data_mean = pd.rolling_mean(data, window=5).shift(-2) print(data_mean) 

gives

 0 NaN 1 NaN 2 3 3 4 4 5 5 6 6 NaN 7 NaN dtype: float64 

As kadee points out , if you want to center the moving average, use

 pd.rolling_mean(data, window=5, center=True) 
+17
source

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


All Articles