Transposing NumPy array

Transposing numpy array is extremely simple using np.transpose function. Fundamentally, transposing numpy array only make sense when you have array of 2 or more than 2 dimensions.

Import numpy package

Before moving ahead, you have a look at my posts on Creating NumPy Array for Beginners and Reshaping NumPy Array.

Transposing a Vector

array([0, 1, 2, 3, 4, 5, 6, 7, 8])
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

Here you can see that transposed vector is the same array. Mainly because transpose of a 1 dimensional array is still a 1 dimensional array.

You can always convert vector to 2D arrays using np.newaxis and than transpose it.

(1, 3)
array([[1, 2, 3]])

You can notice that above vector is converted in 2D array with shape of (1, 3).

(3, 1)
array([[1],
           [2],
           [3]])

Transposing 1D array to 2D column matrix using reshape

[0 1 2]

array([[0],
           [1],
           [2]])

Transposing 1D array to 2D column matrix using vstack

array([[0],
           [1],
           [2]])

Transposing a Matrix

array([[1, 1, 1],
           [2, 2, 2],
           [3, 3, 3]])
array([[1, 2, 3],
           [1, 2, 3],
           [1, 2, 3]])

Transposing numpy array with 3 dimensions (tensors)

(2, 2, 2)
array([[[1, 5],
            [3, 7]],

           [[2, 6],
            [4, 8]]])

 

Leave a Reply

Your email address will not be published. Required fields are marked *