3

For example, there is a 4*2 matrix:

[[1, 2], [3, 4], [5, 6],[7,8]]

I want to reshape it to 2*2 matrix and the value of it is the mean value of the original matrix, so the result will be:

[[2,3],[6,7]]

Is there any effective way to do it? Thanks

1 Answer 1

2

You can reshape the array to 3d and then take mean along the second axis:

a = np.array([[1, 2], [3, 4], [5, 6],[7,8]])
step = 2

a.reshape(-1, step, a.shape[-1]).mean(1)
#array([[ 2.,  3.],
#       [ 6.,  7.]])

Or use np.add.reduceat to add every two rows and then divide by 2:

step = 2
np.add.reduceat(a, np.arange(0,len(a),step))/step
#array([[ 2.,  3.],
#       [ 6.,  7.]])
Sign up to request clarification or add additional context in comments.

Comments

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.