Transpose arrays and swap axes#

Transpose is a special form of reshaping that also provides a view of the underlying data without copying anything. Arrays have the Transpose method and also the special T attribute:

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

numpy.dot returns the scalar product of two arrays, for example:

[7]:
np.dot(reshaped_data.T, reshaped_data)
[7]:
array([[224, 248, 272, 296],
       [248, 276, 304, 332],
       [272, 304, 336, 368],
       [296, 332, 368, 404]])

The @ infix operator is another way to perform matrix multiplication. It implements the semantics of the @ operator introduced in Python 3.5 with PEP 465 and is an abbreviation of np.matmul.

[8]:
data.T @ data
[8]:
1240

For higher dimensional arrays, transpose accepts a tuple of axis numbers to swap the axes:

[9]:
array_3d = np.arange(16).reshape((2, 2, 4))
[10]:
array_3d
[10]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

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

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

Here the axes have been reordered with the second axis in first place, the first axis in second place and the last axis unchanged.

ndarray also has a swapaxes method that takes a pair of axis numbers and swaps the specified axes to rearrange the data:

[12]:
array_3d.swapaxes(1, 2)
[12]:
array([[[ 0,  4],
        [ 1,  5],
        [ 2,  6],
        [ 3,  7]],

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