本文介绍了如何使用NumPy计算移动平均线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
似乎没有函数可以简单地计算numpy/scipy上的移动平均值,从而导致复杂的解决方案.
There seems to be no function that simply calculates the moving average on numpy/scipy, leading to convoluted solutions.
我的问题有两个:
- 用numpy(正确)实现移动平均值的最简单方法是什么?
- 由于这似乎很简单且容易出错,因此有充分的理由不使用在这种情况下包括电池?
如果您只想要直接的非加权移动平均值,则可以使用np.cumsum轻松实现,可能是 比基于FFT的方法快:
If you just want a straightforward non-weighted moving average, you can easily implement it with np.cumsum, which may be is faster than FFT based methods:
编辑更正了Bean在代码中发现的错误的一对一错误索引. 编辑
EDIT Corrected an off-by-one wrong indexing spotted by Bean in the code. EDIT
def moving_average(a, n=3) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n >>> a = np.arange(20) >>> moving_average(a) array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18.]) >>> moving_average(a, n=4) array([ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5])所以我想答案是:它真的很容易实现,也许numpy的专用功能已经有点肿了.
So I guess the answer is: it is really easy to implement, and maybe numpy is already a little bloated with specialized functionality.
更多推荐
如何使用NumPy计算移动平均线?
发布评论