Averaging numpy array over for loop?

Question:

I am calculating a numpy array each iteration of a for loop. How do I average that?

For example:

for i in range(5):
    array_that_I_calculate = some_calculation(x,y,z)
Asked By: user2

||

Answers:

Try this –

  1. Append the array_that_I_calculate at each iteration into a list_of_arrays
  2. After the loop ends, take np.average() of list_of_arrays over axis=0
import numpy as np


##### IGNORE #####
#dummy function that returns (2000,1) array

def some_calculation(x=None,y=None,z=None)
    return np.random.random((2000,1))


##### SOLUTION #####

list_of_arrays = []                                  #<-----

for i in range(5):
    array_that_I_calculate = some_calculation(x,y,z)
    list_of_arrays.append(array_that_I_calculate)    #<-----
    
averaged_array = np.average(list_of_arrays, axis=0)  #<-----
print(averaged_array.shape)
(2000,1)
Answered By: Akshay Sehgal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.