通过C或Python移动平均3个元素

我想计算3个元素的移动平均值。

例如,我有25个销售数据元素。 我需要计算从平均这25个数据元素中获取的移动平均值。

当一个真实数组作为数据给出时,我想编写一个程序来确定3个元素的移动平均值并创建一个数组。 数组中的元素数量比给定的序列短2个元素。 例如,如果给我:

[7.0, 9.0, 5.0, 1.0, 3.0] 

我想得到:

 [7.0, 5.0, 3.0] 

您可以使用Python deque执行此操作,如下所示:

 from collections import deque prices = [7.0, 9.0, 5.0, 1.0, 3.0] moving_average = deque() total = 0.0 days = 3 averages = [] for price in prices: moving_average.append(price) total += price if len(moving_average) > days: # Length of moving average total -= moving_average.popleft() averages.append(total / float(len(moving_average))) print averages 

这将显示以下输出:

 [7.0, 8.0, 7.0, 5.0, 3.0] 

或者您可以跳过初始条目,如下所示:

 print averages[days-1:] 

赠送:

 [7.0, 5.0, 3.0] 

最好的(也是最快的,到目前为止)解决这个问题的方法是卷积 。 使用numpy的卷积 :

 import numpy as np x = np.asarray([7.0, 9.0, 5.0, 1.0, 3.0]) # create what's known as the convolution 'kernel' # note that this sums to 1, which results in an average kernel = np.ones(3) / 3 # do the convolution to compute the moving average moving_avg = np.convolve(x, kernel, mode='valid') 

您可以将卷积操作视为内核在数据序列上“滑动”。 当内核以该点k为中心时,卷积输出中的每个点moving_avg[k]将是数据与内核之间的乘积下的区域。

这是一个动画(来自上面链接的维基百科文章),说明了移动平均计算中使用的平方内核的原理:

在此处输入图像描述

列表理解是一种pythonic方法,它不需要任何导入:

 >>> a [7, 9, 5, 1, 3] >>> [(a[i]+a[i+1]+a[i+2])/3.0 for i in xrange(len(a)-2)] [7.0, 5.0, 3.0]