Amer
Amer

Reputation: 335

Reshape numpy array from 3D to 2D

I have a an array that is of shape (5,2,1)

array([[[-0.00047776],
    [-0.00065181]],

   [[-0.00065181],
    [ 0.00130446]],

   [[ 0.00130446],
    [ 0.00151989]],

   [[ 0.00151989],
    [ 0.00121407]],

   [[ 0.00121407],
    [-0.00121259]]], dtype=float32)

I want to convert it to shape (2,5,1) like this

        array([

                [[-0.00047776], [-0.00065181], [ 0.00130446], [ 0.00151989], [ 0.00121407]], 
                [[-0.00065181], [ 0.00130446], [ 0.00151989], [ 0.00121407], [-0.00121259]]


            ])

Thanks

Upvotes: 1

Views: 485

Answers (1)

unutbu
unutbu

Reputation: 879083

Every NumPy array has a natural 1D order to its items. This is the order that you see when you ravel the array. Reshaping (with the default order='C') does not change the order of the items in the array. Therefore, x.reshape(shape) is the same as x.ravel().reshape(shape). The key take-away message here is that an array y is "reachable" via reshaping x if and only if y.ravel() equals x.ravel().

So consider the raveled (1-dimensional) order of the items in the given array and the desired array:

In [21]: x = np.array([[[-0.00047776], [-0.00065181]], [[-0.00065181], [ 0.00130446]], [[ 0.00130446], [ 0.00151989]], [[ 0.00151989], [ 0.00121407]], [[ 0.00121407], [-0.00121259]]], dtype=np.float32); x.ravel()
Out[21]: 
array([-0.00047776, -0.00065181, -0.00065181,  0.00130446,  0.00130446,
        0.00151989,  0.00151989,  0.00121407,  0.00121407, -0.00121259], dtype=float32)

versus

In [22]: y = np.array([ [[-0.00047776], [-0.00065181], [ 0.00130446], [ 0.00151989], [ 0.00121407]], [[-0.00065181], [ 0.00130446], [ 0.00151989], [ 0.00121407], [-0.00121259]] ]); y.ravel()
Out[22]: 
array([-0.00047776, -0.00065181,  0.00130446,  0.00151989,  0.00121407,
       -0.00065181,  0.00130446,  0.00151989,  0.00121407, -0.00121259])

Notice that the item order is different. Thus, to achieve the desired array, you must first (somehow) reorder the items in x. In this case using swapaxes to swap the first and second axes does the trick:

In [23]: x.swapaxes(0,1)
Out[25]: 
array([[[-0.00047776],
        [-0.00065181],
        [ 0.00130446],
        [ 0.00151989],
        [ 0.00121407]],

       [[-0.00065181],
        [ 0.00130446],
        [ 0.00151989],
        [ 0.00121407],
        [-0.00121259]]], dtype=float32)

In [26]: np.allclose(x.swapaxes(0,1), y)
Out[26]: True

No reshape is necessary since x.swapaxes(0,1) already has shape (2,5,1).

Upvotes: 2

Related Questions