我正在尝试计算包含 NaN 的大型 numpy 数组中的移动平均值。目前我正在使用:
import numpy as np
def moving_average(a,n=5):
ret = np.cumsum(a,dtype=float)
ret[n:] = ret[n:]-ret[:-n]
return ret[-1:]/n
使用屏蔽数组计算时:
x = np.array([1.,3,np.nan,7,8,1,2,4,np.nan,np.nan,4,4,np.nan,1,3,6,3])
mx = np.ma.masked_array(x,np.isnan(x))
y = moving_average(mx).filled(np.nan)
print y
>>> array([3.8,3.8,3.6,nan,nan,nan,2,2.4,nan,nan,nan,2.8,2.6])
我正在寻找的结果(下面)理想情况下应该只在原始数组 x 有 NaN 的地方有 NaN,并且应该对分组中的非 NaN 元素的数量进行平均(我需要一些改变函数中 n 大小的方法。)
y = array([4.75,4.75,nan,4.4,3.75,2.33,3.33,4,nan,nan,3,3.5,nan,3.25,4,4.5,3])
我可以遍历整个数组并逐个索引检查,但我使用的数组非常大,这会花费很长时间。有没有一种 numpythonic 的方法可以做到这一点?
最佳答案
Pandas 在这方面有很多非常好的功能。例如:
x = np.array([np.nan, np.nan, 3, 3, 3, np.nan, 5, 7, 7])
# requires three valid values in a row or the resulting value is null
print(pd.Series(x).rolling(3).mean())
#output
nan,nan,nan, nan, 3, nan, nan, nan, 6.333
# only requires 2 valid values out of three for size=3 window
print(pd.Series(x).rolling(3, min_periods=2).mean())
#output
nan, nan, nan, 3, 3, 3, 4, 6, 6.3333
您可以尝试使用 windows/min_periods 并考虑在一个链接的代码行中全部填充空值。
关于python - 使用 NaNs 计算 numpy 数组中的移动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919050/