Calculate mean of each 2d array in a numpy array

Viewed 2499

I have an numpy array as following:

b = numpy.array([[[1,2,3], [4,5,6]], [[1,1,1],[3,3,3]]])
print(b)
[[[1 2 3]
  [4 5 6]]

 [[1 1 1]
  [3 3 3]]]

now I wan't to calculate the mean of each 2-d array in the array. for e.g.

numpy.mean(b[0])
>>> 3.5
numpy.mean(b[1])
>>> 2.0

How do I do this without using a for loop?

2 Answers

np.mean() can take in parameters for the axis, so according to your use, you can do either of the following

print("Mean of each column:")
print(x.mean(axis=0))
print("Mean of each row:")
print(x.mean(axis=1))
Related