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]
CodePudding user response:
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())
CodePudding user response:
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)