0

I have a for loop (100 passes) which generates a numpy array during each pass. Is there a way to add these 100 arrays (element wise) and then calculate the array which represents the average of these 100 arrays?

2
  • 1
    One option is to collect the arrays in a list, and make a multidimensional array from that. Then it's easy to apply np.mean along the right axis. But if all you need is the mean, you could sum at each step, e.g. total += new_array, and get the mean from that sum. Commented Dec 13, 2021 at 8:02
  • @ hpaulj -- Thank you! The np.mean suggestion works well. I had not collected the arrays correctly as a list, so was caught up. Now, it's resolved. Commented Dec 13, 2021 at 8:25

1 Answer 1

2

Perhaps you're looking for:

np.mean(arr, axis=0)

Alternatively, you can do:

np.sum(arr, axis=0) / len(arr)

Here, arr is the array you created with the loop.

You can define arr as:

arr = []
for i in range(100):
    # create numpy array here and assign it to x
    arr.append(x)

Then you can do np.mean etc on arr.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.