Saqib Ali
Saqib Ali

Reputation: 4448

Calculate mean of each 2d array in a numpy array

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?

Upvotes: 2

Views: 4049

Answers (2)

Dishin H Goyani
Dishin H Goyani

Reputation: 7723

I think this would give you your expected output

By passing multi-dim in axis - see doc for more about axis param

b.mean(axis=(1,2))
array([3.5, 2. ])

Upvotes: 4

Ravish Jha
Ravish Jha

Reputation: 445

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))

Upvotes: 2

Related Questions