Process matrix in python

For example, there is a 4 * 2 matrix:

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

      

I want to change it to a 2 * 2 matrix and the value of this value is the average of the original matrix, so the result will be:

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

      

Is there an efficient way to do this? Thanks to

+3


source to share


1 answer


You can change the matrix to 3d and then take the average 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 lines and then split by 2:

step = 2
np.add.reduceat(a, np.arange(0,len(a),step))/step
#array([[ 2.,  3.],
#       [ 6.,  7.]])

      

+2


source







All Articles