Home > Net >  How to reshape 3d numpy table?
How to reshape 3d numpy table?

Time:10-29

I have a 3d numpy table with shape=(2,3,4) like below:

a = np.array([[[1., 2., 3., 4.],
        [1., 2., 3., 4.],
        [1., 2., 3., 4.]],

       [[5., 6., 7., 8.],
        [5., 6., 7., 8.],
        [5., 6., 7., 8.]]])

And want to reshape this in a way where the columns in each dimension are stacked into a new column in a 2d matrix.

1  5
1  5
1  5
2  6
2  6
2  6
3  7
3  7
3  7
4  8
4  8
4  8

CodePudding user response:

Here you go:

res = a.T.reshape((-1,2))

Output:

array([[1., 5.],
       [1., 5.],
       [1., 5.],
       [2., 6.],
       [2., 6.],
       [2., 6.],
       [3., 7.],
       [3., 7.],
       [3., 7.],
       [4., 8.],
       [4., 8.],
       [4., 8.]])

CodePudding user response:

To reshape a numpy array, use the reshape method.

Basically it looks at the array as it was flattened and works over it with the new given shape. It does however iterates over the last index first, ie, the inner-most list will be processed, then the next and so on.

So both a np.array([1, 2, 3, 4, 5, 6]).reshape((3, 2)) and a np.array([[1, 2, 3], [4, 5, 6]]).reshape((3, 2)) will give [[1, 2], [3, 4], [5, 6]], since these two originating arrays are the same when flattened.

You want a (12, 2) array, or if you read the reshape docs, you can pass (-1, 2) and numpy will figure the other dimension.

So if you just give the new shape for your array as is, it will start working with the first list x[0, 0] = [1, 2, 3, 4], which would become [[1, 2], [3, 4]], ... That's not what you want.

But note that if you transpose your array first, then you'll have the items you want in the inner lists (fast varying index):

In : x.T
Out: 
array([[[1., 5.],
        [1., 5.],
        [1., 5.]],

       [[2., 6.],
        [2., 6.],
        [2., 6.]],

       [[3., 7.],
        [3., 7.],
        [3., 7.]],

       [[4., 8.],
        [4., 8.],
        [4., 8.]]])

Which is almost what you want, except for the extra dimension. So now you can just reshape this and get your (12, 2) array the way you want:

In : x.T.reshape((-1, 2))
Out: 
array([[1., 5.],
       [1., 5.],
       [1., 5.],
       [2., 6.],
       [2., 6.],
       [2., 6.],
       [3., 7.],
       [3., 7.],
       [3., 7.],
       [4., 8.],
       [4., 8.],
       [4., 8.]])
  • Related