2014-03-03 56 views
2

我试图计算滚动平均值与NaN的大熊猫中的数据帧,但大熊猫似乎重置时,它满足楠窗口,听到一些代码为例...在熊猫中计算序列滚动平均值作为数组函数?

import numpy as np 
from pandas import * 

foo = DataFrame(np.arange(0.0,13.0)) 
foo['1'] = np.arange(13.0,26.0) 
foo.ix[4:6,0] = np.nan 
foo.ix[4:7,1] = np.nan 
bar = rolling_mean(foo, 4) 

给人的滚动平均值该复位后每个NaN的窗口,而不是仅仅跳过了NaN的

bar = 
     0  1 
0 NaN NaN 
1 NaN NaN 
2 NaN NaN 
3 1.5 14.5 
4 NaN NaN 
5 NaN NaN 
6 NaN NaN 
7 NaN NaN 
8 NaN NaN 
9 NaN NaN 
10 8.5 NaN 
11 9.5 22.5 
12 10.5 23.5 

我已经找到了一个丑陋的ITER/dropna()解决给出正确的答案

def sparse_rolling_mean(df_data, window): 
    ...:  f_data = DataFrame(np.nan,index=df_data.index, columns=df_data.columns) 
    ...:  for i in f_data.columns: 
    ...:   f_data.ix[:,i] = rolling_mean(df_data.ix[:,i].dropna(),window) 
    ...:  return f_data 

bar = sparse_rolling_mean(foo,4) 

bar 
     0  1 
0  NaN NaN 
1  NaN NaN 
2  NaN NaN 
3 1.50 14.5 
4  NaN NaN 
5  NaN NaN 
6  NaN NaN 
7 3.25 NaN 
8 5.00 16.5 
9 6.75 18.5 
10 8.50 20.5 
11 9.50 22.5 
12 10.50 23.5 

有没有人知道是否有可能做到这一点作为一个数组功能? 非常感谢提前。

回答

2

你可以这样做:

>>> def sparse_rolling_mean(ts, window): 
...  return rolling_mean(ts.dropna(), window).reindex_like(ts) 
... 
>>> foo.apply(sparse_rolling_mean, args=(4,)) 
     0  1 
0  NaN NaN 
1  NaN NaN 
2  NaN NaN 
3 1.50 14.5 
4  NaN NaN 
5  NaN NaN 
6  NaN NaN 
7 3.25 NaN 
8 5.00 16.5 
9 6.75 18.5 
10 8.50 20.5 
11 9.50 22.5 
12 10.50 23.5 

[13 rows x 2 columns] 
+0

嗨behzad.nouri,这个工程,比我的方法更有效率,非常感谢 – Lonewolf

+0

这个方法可以应用到Panel结构吗? – Lonewolf

0

你可以控制得到真实naned出与min_periods ARG

In [12]: rolling_mean(foo, 4,min_periods=1) 
Out[12]: 
     0  1 
0 0.0 13.0 
1 0.5 13.5 
2 1.0 14.0 
3 1.5 14.5 
4 2.0 15.0 
5 2.5 15.5 
6 3.0 16.0 
7 7.0 NaN 
8 7.5 21.0 
9 8.0 21.5 
10 8.5 22.0 
11 9.5 22.5 
12 10.5 23.5 

[13 rows x 2 columns] 

,如果你想要的结果,除非原来是南

你可以这样做
In [27]: rolling_mean(foo, 4,min_periods=1)[foo.notnull()] 
Out[27]: 
     0  1 
0 0.0 13.0 
1 0.5 13.5 
2 1.0 14.0 
3 1.5 14.5 
4 NaN NaN 
5 NaN NaN 
6 NaN NaN 
7 7.0 NaN 
8 7.5 21.0 
9 8.0 21.5 
10 8.5 22.0 
11 9.5 22.5 
12 10.5 23.5 

[13 rows x 2 columns] 

您的预期有点奇怪,因为前3行应该有价值秒。

+0

你好杰夫,正在玩最小时间段,当你设置min_periods = 1时,它似乎在NaN之后执行类似expanding_mean(),直到它达到窗口的长度。你的例子中的[0,7]是7(len 1)和bar [0,8]的平均值是(7 + 8)/ 2。认为这就是为什么你有价值0:3,而我不 – Lonewolf

+0

换言之,我们有不同的手段在我们的输出NaNs后 – Lonewolf

相关问题