[英]How to implement a moving average?
I've got a distribution of numbers in an array called predictions
and I wanted a moving average.我在一个叫做
predictions
的数组中得到了一个数字分布,我想要一个移动平均线。 I am new to Python, so I've not used numpy
here, just ordinary arrays.我是 Python 新手,所以我没有在这里使用
numpy
,只是普通的数组。 My question is there a more graceful way of doing this?我的问题是有更优雅的方式来做到这一点吗?
Here is the code:这是代码:
predictions = [] #Already filled with 7001 values
movingaverage = []
pmean = []
n=-1
count = 0
sumpm = 0
for z in range(40000):
n+=1
count+=1
pmean.append(predictions[n])
if(count == 5):
for j in range(5):
sumpm+=pmean[j]
sumpm=sumpm/5
movingaverage.append(sumpm)
n=n-5
pmean = []
sumpm=0
count = -1
The size of predictions array is 7001 or can use len(predictions)
.预测数组的大小为 7001 或可以使用
len(predictions)
。
Here is something I wrote in the past这是我过去写的东西
def moving_average(a: list, n: int) -> list:
"""
:param a: array of numbers
:param n: window of the moving average
:return: the moving average sequence
"""
moving_sum = sum(a[:n])
moving_averages = [moving_sum/n]
for i in range(n, len(a)):
moving_sum += a[i] - a[i - n]
moving_averages.append(moving_sum / n)
return moving_averages
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.