Home > Software design >  Numpy array reshape element-wise
Numpy array reshape element-wise

Time:07-28

I have a 3-D array size = (3,2,3)

[
 [[1, 2, 3],[4, 5, 6]],
 [[7, 8, 9],[10,11,12]],
 [[13,14,15],[16,17,19]]
]

How to reshape to (3,3,2):

[
 [[1,4], [2,5], [3,6]],
 [[7,10], [8,11], [9,12],],
 [[13,16],[14,17],[15,19]]
]

CodePudding user response:

x = [[[1, 2, 3],[4, 5, 6]],
     [[7, 8, 9],[10,11,12]],
     [[13,14,15],[16,17,19]]]
res = [[[i,j] for (i,j) in zip(sub[0], sub[1])] for sub in x]

CodePudding user response:

You task is not to reshape the array. You have to swap the last axis (the third dimension of your array) with the second.

import numpy as np

#input
arr = np.array([
 [[1, 2, 3],[4, 5, 6]],
 [[7, 8, 9],[10,11,12]],
 [[13,14,15],[16,17,19]]
])

#output
np.moveaxis(arr, 2, 1)

#an alternative is
np.swapaxes(arr, 1, 2)
  • Related