首先,什么是移动平均数呢?(来自百度百科)
若依次得到测定值
时,按顺序取一定个数所做的全部算术平均值。 例如
等是移动平均值
详细可以点击此处链接
Python中是如何实现呢?
Python中有个一个现有的类, deque.这个一个双向队列。我们知道,队列具有先进先出的特点。
算法原理是:
假设一组数据是:[40, 30, 50, 46, 39, 44]
1、首先可以截取原数据前2个初始化队列,d = [40, 30], array = [50, 46, 39, 44]
2、开始遍历数组,每次遍历的时候,在d上面加上当前遍历的数据,同时去掉队列中第一个。
deque([40, 30, 50])
deque([30, 50, 46])
deque([50, 46, 39])
deque([46, 39, 44])
Python代码:
def moving_average(data_array, n=3):
"""
Calcuate the moving average based on the specific data array.
:param data_array: the array stored data to be calculated.
:param n: the number of data in one time
:return: Generate which contains the result
"""
it = iter(data_array)
d = deque(itertools.islice(it, n - 1))
s = sum(d)
# In the first round, to avoid getting extra element, so need zero in the head of queue.
d.appendleft(0)
for elem in it:
s += elem - d.popleft()
d.append(elem)
yield s / float(n)
测试:
if __name__ == '__main__':
lst = [40, 30, 50, 46, 39, 44]
it = moving_average(lst)
print(list(it))
# [40.0, 42.0, 45.0, 43.0]
代码注释:
1、iter()把列表变为一个可迭代对象
2、itertools.islice(iterable, n) 表示获取interable中的前N个数据
3、deque.popleft就是移出最左边的一个数据,返回值就是移出的数据。
版权声明:本文为sxb0841901116原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。