python中的滚动函数忽略nans

Jun*_*mad 3 python pandas

https://pandas.pydata.org/pandas-docs/version/0.17.0/ generated/pandas.rolling_quantile.html

我不知道如何最好地忽略滚动百分位函数中的 NaN。有人知道吗?

seriestest = pd.Series([1, 5, 7, 2, 4, 6, 9, 3, 8, 10])
Run Code Online (Sandbox Code Playgroud)

并插入 nan

seriestest2 = pd.Series([1, 5, np.NaN, 2, 4, np.nan, 9, 3, 8, 10])
Run Code Online (Sandbox Code Playgroud)

现在,在第一个系列中,我使用以下方法获得了预期输出:

seriestest.rolling(window = 3).quantile(.5)
Run Code Online (Sandbox Code Playgroud)

但是,我希望做同样的事情并忽略 test2 系列上的 NaN。

seriestest2.rolling(window = 3).quantile(.5)
Run Code Online (Sandbox Code Playgroud)

给出:

0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN
6    NaN
7    NaN
8    8.0
9    8.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

但我认为如果我们可以解析 a skipna=True,它会给出类似这样的东西,这对我不起作用:

0    NaN
1    NaN
2    5.0
3    2.0
4    4.0
5    4.0
6    4.0
7    3.0
8    8.0
9    8.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

bus*_*ear 7

问题是,拥有nan值会给您提供的元素数量少于滚动窗口中所需的元素数量 (3)。您可以通过设置参数将有效观测值的最小数量定义为rollingless min_periods

seriestest2.rolling(window=3, min_periods=1).quantile(.5)
Run Code Online (Sandbox Code Playgroud)

nan或者,如果您只是想用 say替换值0,您可以使用fillna

seriestest2.fillna(value=0).rolling(window=3).quantile(.5)
Run Code Online (Sandbox Code Playgroud)