Reputation: 3472
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.
Upvotes: 1
Views: 97
Reputation: 7267
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
.
Upvotes: 2