[英]Rolling mean with customized window with Pandas
Is there a way to customize the window of the rolling_mean function? 有没有办法自定义rolling_mean函数的窗口?
data
1
2
3
4
5
6
7
8
Let's say the window is set to 2, that is to calculate the average of 2 datapoints before and after the obervation including the observation. 假设窗口设置为2,即计算观察前后的2个数据点的平均值。 Say the 3rd observation. 说第3次观察。 In this case, we will have (1+2+3+4+5)/5 = 3
. 在这种情况下,我们将有(1+2+3+4+5)/5 = 3
。 So on and so forth. 等等等等。
Compute the usual rolling mean with a forward (or backward) window and then use the shift
method to re-center it as you wish. 使用向前(或向后)窗口计算通常的滚动平均值,然后使用shift
方法根据需要重新定位它。
data_mean = pd.rolling_mean(data, window=5).shift(-2)
If you want to average over 2 datapoints before and after the observation (for a total of 5 datapoints) then make the window=5
. 如果要在观察前后平均超过2个数据点(总共5个数据点),则使window=5
。
For example, 例如,
import pandas as pd
data = pd.Series(range(1, 9))
data_mean = pd.rolling_mean(data, window=5).shift(-2)
print(data_mean)
yields 产量
0 NaN
1 NaN
2 3
3 4
4 5
5 6
6 NaN
7 NaN
dtype: float64
As kadee points out , if you wish to center the rolling mean, then use 正如kadee指出的那样 ,如果你希望将滚动平均值居中,那么就使用
pd.rolling_mean(data, window=5, center=True)
For more current version of Pandas (please see 0.23.4 documentation https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html ), you don't have rolling_mean anymore. 对于更新版本的Pandas(请参阅0.23.4文档https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html ),您不再拥有rolling_mean。 Instead, you will use 相反,你会使用
DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None)
For your example, it will be: 对于您的示例,它将是:
df.rolling(5,center=True).mean()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.