Home > Software engineering >  Averaging numpy array over for loop?
Averaging numpy array over for loop?

Time:01-09

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)

CodePudding user response:

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)
  • Related