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

np.transpose behavior different for different array constructions

I came across this weird behavior with np.transpose wherein it works differently when used on an numpy array and array constructed from a list. As an MWE following code is presented.

import numpy as np

a = np.random.randint(0, 5, (1, 2, 3))
print(a.shape)
# prints (1, 2, 3)
b = np.transpose(a, (0, 2, 1))
print(b.shape)
# prints (1, 3, 2), which is expected

# Constructing array from list of arrays
c = np.array([np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3))])
print(c.shape)
# prints (4, 2, 3)
d = np.transpose(c, (2, 0, 1))
print(d.shape)
# prints (3, 4, 2), whereas I expect it to be (2, 3, 4)

I do not understand this behavior. Why is it that the array constructed from the list has the dimensions mixed up? Any help is appreciated.

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

>Solution :

np.transpose() picks the dimensions you specify in the order you specify.

In your first case, your array shape is (1,2,3) i.e. in dimension->value format, it is 0 -> 1, 1 -> 2 and 2 -> 3. In np.transpose(), you’re requesting for the order 0,2,1 which is 1,3,2.

In the second case, your array shape is (4,2,3) i.e. in dimension->value format, it is 0 -> 4, 1 -> 2 and 2 -> 3. In np.transpose(), you’re requesting for the order 2,0,1 which is 3,4,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