3 个元素的移动平均值 C 或 Python
moving average of 3 elements by C or Python
我想计算3个元素的移动平均数。
比如我有一个25个元素的销售数据。我需要计算从这 25 个数据元素中取平均值的移动平均值。
当给出一个真实数组作为数据时,我想编写一个程序来确定 3 元素移动平均线并创建一个数组。数组中的元素数变为比给定序列短 2 个元素。
例如,如果我得到:
[7.0, 9.0, 5.0, 1.0, 3.0]
我想得到:
[7.0, 5.0, 3.0]
解决此问题的最佳(也是最快的)方法是 convolution. Using numpy's convolve:
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')
您可以将卷积运算视为数据序列上的内核 "sliding"。卷积输出中的每个点 moving_avg[k]
都将是您的数据和内核之间的乘积下的区域,当内核以该点为中心时 k
.
这是一个动画(来自上面链接的维基百科文章),说明了移动平均计算中使用的平方核的原理:
您可以使用 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]
列表理解是一种执行此操作的 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]
我想计算3个元素的移动平均数。
比如我有一个25个元素的销售数据。我需要计算从这 25 个数据元素中取平均值的移动平均值。
当给出一个真实数组作为数据时,我想编写一个程序来确定 3 元素移动平均线并创建一个数组。数组中的元素数变为比给定序列短 2 个元素。 例如,如果我得到:
[7.0, 9.0, 5.0, 1.0, 3.0]
我想得到:
[7.0, 5.0, 3.0]
解决此问题的最佳(也是最快的)方法是 convolution. Using numpy's convolve:
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')
您可以将卷积运算视为数据序列上的内核 "sliding"。卷积输出中的每个点 moving_avg[k]
都将是您的数据和内核之间的乘积下的区域,当内核以该点为中心时 k
.
这是一个动画(来自上面链接的维基百科文章),说明了移动平均计算中使用的平方核的原理:
您可以使用 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]
列表理解是一种执行此操作的 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]