2

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?

Saqib Ali
  • 3,953
  • 10
  • 55
  • 100

2 Answers2

4

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. ])
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
2

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))
Ravish Jha
  • 481
  • 3
  • 25
  • To expand on this: Axis of 0 is rows, 1 is columns. You iterate over rows to compute the sum of each column and you iterate over columns to compute the sum of each row which is how you get the code above. – J.Doe Sep 05 '21 at 03:06