2017-06-06 5 views
1

j'ai une très simple série Pandas:pandas géants roulant appliquer pour permettre nan

xx = pd.Series([1, 2, np.nan, np.nan, 3, 4, 5]) 

Si je cours ce que je ce que je veux:

>>> xx.rolling(3,1).mean() 
0 1.0 
1 1.5 
2 1.5 
3 2.0 
4 3.0 
5 3.5 
6 4.0 

Mais si je dois utiliser .apply() Je ne peux pas le faire fonctionner en ignorant NaN s dans l'opération mean():

>>> xx.rolling(3,1).apply(np.mean) 
0 1.0 
1 1.5 
2 NaN 
3 NaN 
4 NaN 
5 NaN 
6 4.0 

>>> xx.rolling(3,1).apply(lambda x : np.mean(x)) 
0 1.0 
1 1.5 
2 NaN 
3 NaN 
4 NaN 
5 NaN 
6 4.0 

Que dois-je faire pour utiliser à la fois .apply() et avoir le résultat dans la première sortie? Mon problème actuel est plus compliqué que je dois utiliser .apply() pour réaliser, mais cela se résume à ce problème.

Répondre

2

Vous pouvez utiliser np.nanmean()

xx.rolling(3,1).apply(lambda x : np.nanmean(x)) 
Out[59]: 
0 1.0 
1 1.5 
2 1.5 
3 2.0 
4 3.0 
5 3.5 
6 4.0 
dtype: float64 

Si vous devez traiter les nans explicitement, vous pouvez faire:

xx.rolling(3,1).apply(lambda x : np.mean(x[~np.isnan(x)])) 
Out[94]: 
0 1.0 
1 1.5 
2 1.5 
3 2.0 
4 3.0 
5 3.5 
6 4.0 
dtype: float64