0

I have an array A with shape (2,4,1). I want to calculate the mean of A[0] and A[1] and store both the means in A_mean. I present the current and expected outputs.

import numpy as np

A=np.array([[[1.7],
        [2.8],
        [3.9],
        [5.2]],

       [[2.1],
        [8.7],
        [6.9],
        [4.9]]])

for i in range(0,len(A)):
    A_mean=np.mean(A[i])
print(A_mean)

The current output is

5.65

The expected output is

[3.4,5.65]
2
  • 1
    A.mean((1, 2)) Commented Sep 10, 2022 at 13:37
  • 1
    the problem is that you overwrite A_mean at each iteration of your loop, instead of appending a new value. @Warkaz's answer is the best solution, but a minimal fix to your loop would have been to first initialize A_mean=[] and then use A_mean.append(np,mean(A[i]) in the body of your loop. Commented Sep 10, 2022 at 13:41

2 Answers 2

2

The for loop is not necessary because NumPy already knows how to operate on vectors/matrices.

solution would be to remove the loop and just change axis as follows:

A_mean=np.mean(A, axis=1)
print(A_mean)

Outputs:

[[3.4 ]
 [5.65]]

Now you can also do some editing to remove the brackets with [3.4 5.65]:

print(A_mean.ravel())
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent answer, taking full advantage of NumPy's internal optimizations. Note that if OP really wants the final results in a list, they could use A_mean = list(np.mean(A, axis=1).ravel()), but keeping the results in an array probably makes more sense for further processing with NumPy tools.
@joanis Thanks for the compliment, I already did add the part about ravel() (last line of code) as that was requested format by the OP
Yes, indeed, I noticed your added ravel() and that was a good idea, thanks for that edit!
1

Try this.

import numpy as np

A=np.array([[[1.7],
        [2.8],
        [3.9],
        [5.2]],

       [[2.1],
        [8.7],
        [6.9],
        [4.9]]])
A_mean = []

for i in range(0,len(A)):
    A_mean.append(np.mean(A[i]))
print(A_mean)

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.