通过避免NaN滚动序列 [英] Rolling over a series by avoiding NaNs

查看:38
本文介绍了通过避免NaN滚动序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的情况下,如何通过避免NaN值来执行滚动计算?

How to perform rolling computation by avoiding NaN values in my case ?

我的系列:

2019-05-01    0.1
2019-05-02    0.2
2019-05-03    NaN
2019-05-04    NaN
2019-05-05    NaN
2019-05-06    0.1
2019-05-07    0.5
2019-05-08    NaN
2019-05-09    0.1
2019-05-10    0.2
2019-05-11    NaN
2019-05-12    NaN
2019-05-13    0.3

我需要以以下方式计算该系列的周期2的平均值:

I need to compute the mean of period 2 of this series in a way that my output is:

2019-05-01     NaN
2019-05-02    0.15
2019-05-03     NaN
2019-05-04     NaN
2019-05-05     NaN
2019-05-06    0.15
2019-05-07    0.30
2019-05-08     NaN
2019-05-09    0.30
2019-05-10    0.15
2019-05-11     NaN
2019-05-12     NaN
2019-05-13    0.25

使用rolling,如果您没有2个后续的非NaN值,则平均值将返回NaN,因此它不起作用(在删除NaNs的结果下方):

Using rolling, if you do not have 2 subsequent non-NaN values, the mean will return NaN so it doesn't work (below the result with dropping NaNs):

2019-05-01     NaN
2019-05-02    0.15
2019-05-03     NaN
2019-05-04     NaN
2019-05-05     NaN
2019-05-06     NaN
2019-05-07    0.30
2019-05-08     NaN
2019-05-09     NaN
2019-05-10    0.15
2019-05-11     NaN
2019-05-12     NaN
2019-05-13     NaN

推荐答案

在您的情况下,先dropna然后rolling reindex返回

In your case dropna first then rolling reindex back

s.dropna().rolling(2).mean().reindex(s.index)
Out[796]: 
2019-05-01     NaN
2019-05-02    0.15
2019-05-03     NaN
2019-05-04     NaN
2019-05-05     NaN
2019-05-06    0.15
2019-05-07    0.30
2019-05-08     NaN
2019-05-09    0.30
2019-05-10    0.15
2019-05-11     NaN
2019-05-12     NaN
2019-05-13    0.25
Name: x, dtype: float64

这篇关于通过避免NaN滚动序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆