numpy array and transpose axis conversion

numpy array and transpose axis conversion

Transposed matrix

>>> import numpy as np
>>> arr=np.arange(15).reshape((3,5))
>>> arr
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> arr.T
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])

Within the product matrix

>>> import numpy as np
>>> arr=np.arange(15).reshape((3,5))
>>> arr
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> arr.T
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])
>>> np.dot(arr.T,arr)
array([[125, 140, 155, 170, 185],
       [140, 158, 176, 194, 212],
       [155, 176, 197, 218, 239],
       [170, 194, 218, 242, 266],
       [185, 212, 239, 266, 293]])

Axis transformation

Dimensional axis transformation

1. The two shafts exchange

>>> import numpy as np
>>> arr=np.arange(15).reshape((3,5))
>>> arr
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> arr.transpose(1,0)#1轴和0轴进行交换
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])

Three axis conversion

>>> arr = np.arange(16).reshape((2, 2, 4))
>>> arr
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])
>>> arr.transpose((1,0,2))
array([[[ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[ 4,  5,  6,  7],
        [12, 13, 14, 15]]])

1. This change somewhat cumbersome, difficult to understand. However, if simplification like, added with P (x, y, z) to represent each dot matrix, then numpy in the x, y, z, respectively, to the corresponding 0,1,2

2. For example, such elements in the original array 0, which is the original coordinate (0,0,0), then the transpose (1,0,2) for this point, is the x, y coordinates interchanged z-coordinate constant, which is the new matrix is ​​still coordinate (0,0,0) unchanged

3. For example, such additional point 4 at this point, which coordinates are (0,1,1), then after its x and y coordinates exchange is (1,0,1), so that its position in the new matrix is (1,0,1)

4. In fact transpose function is the transformation of the original matrix to do this for each point, and finally get a new matrix

Two axis exchange

Switching shaft 2 and the shaft 1

>>> arr
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])
>>> arr.swapaxes(1,2)
array([[[ 0,  4],
        [ 1,  5],
        [ 2,  6],
        [ 3,  7]],

       [[ 8, 12],
        [ 9, 13],
        [10, 14],
        [11, 15]]])
>>> arr
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])

Guess you like

Origin www.cnblogs.com/mengxiaoleng/p/11617244.html