Home > OS >  Convert 2D numpy array into 3D numpy array with 3rd dimension
Convert 2D numpy array into 3D numpy array with 3rd dimension

Time:05-06

I have a numpy array of 2D shape

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

and trying to convert into 3D shape of dimension (3,3,2) i.e,

np.array([[ 1,2,3],
          [7,8,9],
          [13,14,15]])

in 3rd dimension with index 1 and

np.array([[4,5,6],
          [10,11,12],
          [16,17,18]])

in 3rd dimension with index 2.

I tried to reshape as a.reshape(3,3,2) and getting this

array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]],

       [[13, 14, 15],
        [16, 17, 18]]])

Any suggestions to convert this?

CodePudding user response:

Use swapaxes:

a.reshape(3,2,3).swapaxes(0,1)

output:

array([[[ 1,  2,  3],
        [ 7,  8,  9],
        [13, 14, 15]],

       [[ 4,  5,  6],
        [10, 11, 12],
        [16, 17, 18]]])
  • Related