如何使用NumPy计算移动平均线?

编程入门 行业动态 更新时间:2024-10-26 16:35:29
本文介绍了如何使用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计算移动平均线?

本文发布于:2023-10-15 02:28:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   平均   NumPy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!