Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

numpy is double transposition necessary in this specific case?

I have an array

xx = np.arange(24).reshape(2, 12)

array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

and I would like to reshape it, to obtain

array([[[ 0,  1,  2,  3],
        [12, 13, 14, 15]],

       [[ 4,  5,  6,  7],
        [16, 17, 18, 19]],

       [[ 8,  9, 10, 11],
        [20, 21, 22, 23]]])

I can achieve it via

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

xx.T.reshape(3, 4, 2).transpose(0, 2, 1)

But it has to be transposed twice, which seems unnecessary to me. So could somebody confirm that this is the only way of doing it or provide more readable solution otherwise?
Thanks!

>Solution :

It is possible to do a single transpose:

data = np.arange(24).reshape(2, 12)
data = data.reshape(2, 3, 4).transpose(1, 0, 2)

Edit:

I checked this using itertools.permutations and itertools.product:

import itertools
import numpy as np

data = np.arange(24).reshape(2, 12)
desired_data = np.array([[[ 0,  1,  2,  3],
                          [12, 13, 14, 15]],
                         
                         [[ 4,  5,  6,  7],
                          [16, 17, 18, 19]],
                         
                         [[ 8,  9, 10, 11],
                          [20, 21, 22, 23]]])

shapes = [2, 3, 4]
transpose_dims = [0, 1, 2]

shape_permutations = itertools.permutations(shapes)
transpose_permutations = itertools.permutations(transpose_dims)

for shape, transpose in itertools.product(
    list(shape_permutations),
    list(transpose_permutations),
):
    
    new_data = data.reshape(*shape).transpose(*transpose)

    try:
        np.allclose(new_data, desired_data)
    except ValueError as e:
        pass
    else:
        break

print(f"{shape=}, {transpose=}")

shape=(2, 3, 4), transpose=(1, 0, 2)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading