0

I've got a distribution of numbers in an array called predictions and I wanted a moving average. I am new to Python, so I've not used numpy here, just ordinary arrays. 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).

martineau
  • 119,623
  • 25
  • 170
  • 301
s kettle
  • 1
  • 5
  • Look at [How to calculate moving average using NumPy?](https://stackoverflow.com/questions/14313510/how-to-calculate-moving-average-using-numpy) – Aviv Yaniv Aug 24 '20 at 21:18
  • Which one would you like to implement? https://en.m.wikipedia.org/wiki/Moving_average – tevemadar Aug 24 '20 at 21:19

1 Answers1

0

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
Vasil Yordanov
  • 417
  • 3
  • 14