首页 > 解决方案 > Pandas 滚动窗口小于等于

问题描述

我有一个基于三个维度分类的数据框:

>>> df
   a  b  c  d
0  a  b  c  1
1  a  e  x  2
2  a  f  e  3

当我通过以下命令滚动度量 d 时:

>>> df.d.rolling(window = 3).mean()
0    NaN
1    NaN
2    2.0
Name: d, dtype: float64

但我真正想要的是执行一个滚动 <= 给定数字,如果第一个条目的结果本身是相同的数字,然后从第二个条目开始滚动窗口大小为 1,第三个条目滚动对于 2 和从 3 开始的窗口大小,它会滚动 3 个先前窗口的运行平均值。

所以我期待的结果是:

对于数据框:

>>> df
   a  b  c  d
0  a  b  c  1
1  a  e  x  2
2  a  f  e  3

>>> df.d.rolling(window = 3).mean()
0    1 #Since this is the first one and so average of the first number is equal to number itself.
1    1.5 # Average of 1 and 2 as rolling criteria is <= 3
2    2.0 # Since here we have 3 elements so from here on it follows the general trend.
Name: d, dtype: float64

可以这样滚动吗?

标签: pandasdataframe

解决方案


我能够使用以下命令滚动:

>>> df.d.rolling(min_periods = 1, window = 3).mean()
0    1.0
1    1.5
2    2.0
Name: d, dtype: float64

借助min_periods一个可以指定滚动窗口的最小配置计数。


推荐阅读