numpy of transposition (TRANSPOSE) and swap shaft

table of Contents

1.T-- applies to a two-dimensional array

2. transpose-- for high-dimensional arrays

3.swapaxes


There are three ways transpose, transposemethods, Tproperties, and swapaxesmethods.


1.T-- applies to a two-dimensional array

In [1]: import numpy as np

In [2]: arr = np.arange(20).reshape(4,5)  # 生成一个4行5列的数组

In [3]: arr, arr.shape()
Out[3]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
(4, 5)

In [4]: arr.T, arr.T.shape()
Out[4]:
array([[ 0,  5, 10, 15],
       [ 1,  6, 11, 16],
       [ 2,  7, 12, 17],
       [ 3,  8, 13, 18],
       [ 4,  9, 14, 19]])
(5, 4)

2. transpose-- suitable for high-dimensional arrays

For high dimensional array, TRANSPOSE need to use a tuple composed by the shaft number, in order to transpose.

For example, three-dimensional array, it is right dimensions are numbered, namely 0,1,2.

In [0]: arr1 = np.arange(12).reshape(2,2,3)

In [1]: arr1
Out[1]:
array([[[ 0,  1,  2],
        [ 3,  4,  5]],
       [[ 6,  7,  8],
        [ 9, 10, 11]]])

In [2]: arr1.shape 
Out[2]: (2, 2, 3) 

In [3]: arr1.transpose((1,0,2))
Out[3]:
array([[[ 0,  1,  2],
        [ 6,  7,  8]],

       [[ 3,  4,  5],
        [ 9, 10, 11]]])

In [4]: arr1.shape 
Out[4]: (2, 2, 3)  # 相当于将0维和1维进行了维度调换

3.swapaxes

Once we understand that part of the above swapaxesmethods also well understood. It accepts a pair of shaft number. For swapping axes. In fact, that is shapethe parameter.

In [67]: arr2 = np.arange(16).reshape(2,2,4)           
                                                       
In [68]: arr2                                          
Out[68]:                                               
array([[[ 0,  1,  2,  3],                              
        [ 4,  5,  6,  7]],                             
                                                       
       [[ 8,  9, 10, 11],                              
        [12, 13, 14, 15]]])                            
                                                       
In [69]: arr2.shape                                    
Out[69]: (2, 2, 4)                                     
                                                       
In [70]: arr2.swapaxes(1,2)                            
Out[70]:                                               
array([[[ 0,  4],                                      
        [ 1,  5],                                      
        [ 2,  6],                                      
        [ 3,  7]],                                     
                                                       
       [[ 8, 12],                                      
        [ 9, 13],                                      
        [10, 14],                                      
        [11, 15]]])   

 

 

Published 38 original articles · 98 won praise · views 360 000 +

Guess you like

Origin blog.csdn.net/xijuezhu8128/article/details/88554936