1

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

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer and explains a lot. I appreciate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.