【问题标题】:Pandas rolling apply with missing data熊猫滚动适用于缺少数据
【发布时间】:2012-11-04 12:43:44
【问题描述】:

我想对缺失的数据进行滚动计算。

示例代码:(为了简单起见,我给出了一个滚动求和的示例,但我想做一些更通用的事情。)

foo = lambda z: z[pandas.notnull(z)].sum() 
x = np.arange(10, dtype="float")    
x[6] = np.NaN
x2 = pandas.Series(x)    
pandas.rolling_apply(x2, 3, foo)

产生:

0   NaN    
1   NaN
2     3    
3     6    
4     9    
5    12    
6   NaN    
7   NaN    
8   NaN    
9    24

我认为在“滚动”期间,缺少数据的窗口将被忽略以进行计算。我希望得到如下结果:

0   NaN    
1   NaN    
2     3    
3     6    
4     9    
5    12    
6     9    
7    12    
8    15    
9    24

【问题讨论】:

  • 我认为这个问题的部分答案可能是通过在滚动应用函数中使用关键字参数 min_periods 。例如:pandas.rolling_apply(x2, 3, foo, min_periods=1) 有帮助。

标签: python pandas missing-data rolling-computation


【解决方案1】:
In [7]: pandas.rolling_apply(x2, 3, foo, min_periods=2)
Out[7]: 
0   NaN
1     1
2     3
3     6
4     9
5    12
6     9
7    12
8    15
9    24

【讨论】:

  • 对于那些想知道的人,这是来自docsmin_periods: Minimum number of observations in window required to have a value (otherwise result is NA).
猜你喜欢
  • 2021-12-18
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 2018-06-20
相关资源
最近更新 更多