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?

5
  • 2
    np.mean(b, axis=0) or simply b.mean(axis=0) or axis=1 depending if you want to average rows or columns. Commented Aug 20, 2020 at 6:17
  • Or b.mean(0). Commented Aug 20, 2020 at 6:19
  • Does this answer your question? Calculate mean across dimension in a 2D array Commented Aug 20, 2020 at 6:25
  • No, none of these address the question I had. Please note that I have an array of 2D arrays. Not a 2D array. Commented Aug 20, 2020 at 6:37
  • numpy.org/doc/stable/reference/generated/numpy.mean.html Commented Aug 20, 2020 at 6:41

2 Answers 2

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. ])
Sign up to request clarification or add additional context in comments.

4 Comments

skip the loop. no point in looping for an operational like this on a numpy array
Thanks. This is exactly what I was looking for. I understand the FOR loop, but can you please explain the first solution you described?
@PaulH yes, removed it.
@SaqibAli It will performed mean on multiple dims as passed.
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))

1 Comment

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.

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.