0

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)
5
  • whats the shape of the array, can you give some samples? Commented Jan 9, 2023 at 11:35
  • Each array_that_I_calculate is 2000 x 1 Commented Jan 9, 2023 at 11:37
  • and whats your expected outputs shape? Commented Jan 9, 2023 at 11:39
  • An average of each element that is also 2000 x 1 Commented Jan 9, 2023 at 11:42
  • 1
    ohk, just append them to a list and then use np.average over axis 0 of that list of arrays. details in my answer Commented Jan 9, 2023 at 11:43

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

do let me know if that solved your question. feel free to mark the answer if it did. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.