python - 如何计算 Python 3 中的移动平均线?

标签 python python-3.x

假设我有一个列表:

y = ['1', '2', '3', '4','5','6','7','8','9','10']

我想创建一个函数来计算 n 日移动平均值。 因此,如果 n 为 5,我希望我的代码计算前 1-5,将其相加并求平均值,即 3.0,然后继续计算 2-6,计算平均值,这将是 4.0,然后是 3-7、4-8、5-9、6-10。

我不想计算前 n-1 天,所以从第 n 天开始,它会计算前几天。

def moving_average(x:'list of prices', n):
    for num in range(len(x)+1):
        print(x[num-n:num])

这似乎打印出了我想要的:

[]
[]
[]
[]
[]

['1', '2', '3', '4', '5']

['2', '3', '4', '5', '6']

['3', '4', '5', '6', '7']

['4', '5', '6', '7', '8']

['5', '6', '7', '8', '9']

['6', '7', '8', '9', '10']

但是,我不知道如何计算这些列表中的数字。有什么想法吗?

最佳答案

旧版本的 Python 文档中有一个很棒的滑动窗口生成器 itertools examples :

from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result    
    for elem in it:
        result = result[1:] + (elem,)
        yield result

使用移动平均线是微不足道的:

from __future__ import division  # For Python 2

def moving_averages(values, size):
    for selection in window(values, size):
        yield sum(selection) / size

针对您的输入运行这个(将字符串映射到整数)给出:

>>> y= ['1', '2', '3', '4','5','6','7','8','9','10']
>>> for avg in moving_averages(map(int, y), 5):
...     print(avg)
... 
3.0
4.0
5.0
6.0
7.0
8.0

要返回“不完整”集合的第一个 n - 1 次迭代,None,只需扩展 moving_averages 函数一点:

def moving_averages(values, size):
    for _ in range(size - 1):
        yield None
    for selection in window(values, size):
        yield sum(selection) / size

关于python - 如何计算 Python 3 中的移动平均线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14884017/

相关文章:

c++后端使用swig wrapper调用python级别定义的回调

python - plotly :使用模板删除图例标题

python - 引用稍后在代码中创建的对象

Python:如何过滤具有 Item D 和 D 之前的任何 Item 的 ID

mysql - 无法在python中的mysql db中输入记录

python - 我可以在 ORM 事件回调中使用 SQLAlchemy 关系吗?总是没有

python - 如何提取 python Dict 值的每个可能值以列出

python - mail_admins 导致 Django/Apache2 连接被拒绝?

python - 组合/合并具有重复名称的两个数据集

django - 我可以在 Django 1.11 中使用 Python 3.7 吗?