numpy: how to change row array into column array

This seems quite difficult for me. I have tried multiple solution but it didn’t worked

my original array is in this form:

arr = np.array([
    [
        [1, 3, 9, 1],
        [2, 2, 9, 1],
        [1, 1, 6, 4],
    ],
    [
        [3, 3, 3, 4],
        [0, 9, 2, 6],
        [7, 6, 6, 1],
    ]
])

Where as my expected output is:

    arr = np.array(
        [
            [
                [
                    [1],
                    [2],
                    [1],
                ],
                [
                    [3],
                    [2],
                    [1],
                ],
                [
                    [9],
                    [9],
                    [6],
                ],
                [
                    [1],
                    [1],
                    [4],
                ],
            ],


            [
                [
                    [3],
                    [0],
                    [7],
                ],
                [
                    [3],
                    [9],
                    [6],
                ],
                [
                    [3],
                    [2],
                    [6],
                ],
                [
                    [4],
                    [6],
                    [1],
                ],
            ],
   ]
)

How can I achieve above output, i have tried np.reshape(arr, (len(arr[0][0]), len(arr[0]), 1)) and many more but failed to obtain my expected output. Please suggest changes.

>Solution :

Transpose and then expand the axis:

>>> arr.transpose(0, 2, 1)[..., None]
array([[[[1],
         [2],
         [1]],

        [[3],
         [2],
         [1]],

        [[9],
         [9],
         [6]],

        [[1],
         [1],
         [4]]],


       [[[3],
         [0],
         [7]],

        [[3],
         [9],
         [6]],

        [[3],
         [2],
         [6]],

        [[4],
         [6],
         [1]]]])

The shape of the original array is (2, 3, 4), and the shape of the expected array is (2, 4, 3, 1), arr.transpose(0, 2, 1) will swap the lengths of the last two axes (because the positions of the last two numbers of (0, 1, 2) are exchanged here):

>>> arr.transpose(0, 2, 1).shape
(2, 4, 3)

A more intuitive example might be using swapaxes:

>>> arr.swapaxes(1, 2).shape
(2, 4, 3)

Slicing is used to expand the axis, where [..., None] is equivalent to [:, :, :, None] (the number of : depends on your array dimension), which will expand the shape of the array from (a, b, c) to (a, b, c, 1).

Leave a Reply