Pavindu
Pavindu

Reputation: 3112

How a 3D numpy array is tranposed

I'm learning Numpy in this break :-D, and I today came across transpose. I can understand the transpose of a 2D matrix well, but had a hard time understanding the transpose of a 3D matrix (array). Can someone explain me how a4 has been subjected to .transpose() in the following snippet? Sure I can find a pattern here, but I want to know the general principle behind transpose so that I will be able to apply it to a matrix of any dimension. Any help is highly appreciated.

In [84]: a4 = np.random.randint(12,size=(3,2,3))
         a4
         array([[[ 2, 10,  8],
                 [ 1,  4,  9]],

                [[ 9, 10,  2],
                 [10,  5,  9]],

                [[ 0,  5,  2],
                 [ 6,  8,  2]]])

In [85]: a4.T
         array([[[ 2,  9,  0],
                 [ 1, 10,  6]],

                [[10, 10,  5],
                 [ 4,  5,  8]],

                [[ 8,  2,  2],
                 [ 9,  9,  2]]])

Upvotes: 2

Views: 221

Answers (1)

plasmon360
plasmon360

Reputation: 4199

What helps me to think about transpose is to realize that the shape array gets flipped like a mirroring operation when transposed. See below:

a2 = np.random.randint(12,size=(3,2))
print('{} <=> {}'.format(a2.shape, a2.T.shape))

a3 = np.random.randint(12,size=(3,2,4))
print('{} <=> {}'.format(a3.shape, a3.T.shape))

a4 = np.random.randint(12,size=(3,2,4,5))
print('{} <=> {}'.format(a4.shape, a4.T.shape)) 

results in

(3, 2) <=> (2, 3)
(3, 2, 4) <=> (4, 2, 3)
(3, 2, 4, 5) <=> (5, 4, 2, 3)

Upvotes: 2

Related Questions