Search code examples
pythonarraysaverage

Moving average in python array


I have an array 'aN' with a shape equal to (1000,151). I need to calculate the average every 10 data in rows, so I implemented this

arr = aN[:]
window_size = 10
i = 0
moving_averages = []

while i < len(arr) - window_size + 1:
    window_average = round(np.sum(arr[i:i+window_size]) / window_size, 2)      
    moving_averages.append(window_average)
    i += 10

The point is that my output is a list of 100 data, but I need an array with the same number of columns that the original array (151). Any idea on how to get this outcome??

TIA!!


Solution

  • If you convert it to a pandas dataframe, you can use the rolling() function of pandas together with the mean() function. It should be able to accomplish what you need.