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 -
- Append the
array_that_I_calculate
at each iteration into alist_of_arrays
- After the loop ends, take
np.average()
oflist_of_arrays
overaxis=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)