Home > Mobile >  transpose function of numpy
transpose function of numpy

Time:11-28

I am new to numpy and python and I am trying to understand the usage of transpose function of numpy. The code below works fine but I am still not be able to understand the effect of transpose function and also the use of the arguments inside it. It would be great help if someone can explain the usage and effect of transpose function in below code.

import numpy as np
my_list = [[[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,2],[3,4]],[[1,2],[3,4]]]],[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,2],[3,4]],[[1,2],[3,4]]]]], [[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,0],[1,1]],[[1,0],[1,1]]]],[[[[1,0],[1,1]],[[1,0],[1,1]]], [[[1,0],[1,1]],[[1,0],[1,1]]]]]]
arr = np.array(my_list)
perm_testing = [0,1,2,3,4,5]
testing = arr.transpose(perm_testing)
print(testing)

Edit

import numpy as np
my_list = [[1,2],[3,4]]
arr = np.array(my_list)

perm_testing = [1,0]
testing = arr.transpose(perm_testing)
print(testing)

[[1 3]
 [2 4]]

CodePudding user response:

Here's an attempt to visually explain for a 3d-array. I hope it'll help you better understand what's happening:

a=np.arange(24).reshape(2,4,3)

# 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 a visual 3d representation of a (axis 0 corresponds to the first bracket level and to the first size in the shape, and so on for axis 1 and 2):

3d array

a.transpose(1,0,2)  # swapping axis 0 and 1

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

Visual 3d representation of the new array (sorry, my drawing skills are quite limited):

new array

  • Related