np.transpose: How to Reverse Axes of Array in Python

The Numpy transpose() function reverses or permutes the axes of an array, and it returns the modified array. For an array with two axes, transpose(a) gives the matrix transpose. The transpose of the 1D array is still a 1D array. Before we proceed further, let’s learn the difference between Numpy matrices and Numpy arrays.

A ndarray is an (it is usually fixed-size) multidimensional container of elements of the same type and size. The number of dimensions and items in the array is defined by its shape, which is the tuple of N non-negative integers that specify the sizes of each dimension.

The type of elements in the array is specified by a separate data-type object (dtype) associated with each ndarray. As with other container objects in Python, the contents of a ndarray can be accessed and modified by indexing or slicing the array (using, for example, N integers) and via the methods and attributes of the ndarray.

You have to install numpy for this tutorial. Also, check your numpy version as well.

Difference between Numpy Matrices and Numpy Arrays

Numpy matrices are strictly two-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are the subclass of the ndarray, so they inherit all the attributes and methods of ndarrays.

The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if x and y are matrices, then x*y is their matrix product.

On the other hand, as of Python 3.5, Numpy supports infix matrix multiplication using the @ operator so that you can achieve the same convenience of the matrix multiplication with ndarrays in Python >= 3.5.

Both matrix objects and ndarrays have .T to return the transpose, but the matrix objects also have .H for the conjugate transpose and I for the inverse.

In contrast, numpy arrays consistently rule that operations are applied element-wise (except for the new @ operator). Thus, if x and y are numpy arrays, then x*y is the array formed by multiplying the components element-wise.

I hope your doubt on the Numpy array and Numpy Matrix will be clear.

np.transpose

The np.transpose() is a Numpy library function that performs the simple transpose function within one line. The transpose() method can transpose the 2D arrays; on the other hand, it does not affect 1D arrays. Thus, the transpose() method transposes the 2D numpy array.

Syntax

numpy.transpose(a, axes=None)

Parameters

a: array_like

It is the Input array.

axes: tuple or list of ints, optional

If specified, it must be the tuple or list, which contains the permutation of [0,1,.., N-1] where N is the number of axes of a.

The i’th axis of the returned array will correspond to an axis numbered axes[i] of the input.

If not specified, defaults to the range(a.ndim)[::-1], which reverses the order of the axes.

Return value

The transpose() function returns an array with its axes permuted. A view is returned whenever possible.

Example

# app.py

import numpy as np

data = np.arange(6).reshape((2, 3))
print("Original Array")
print(data)

tMat = np.transpose(data)
print("Transposed Array")
print(tMat)

Output

python3 app.py
Original Array
[[0 1 2]
 [3 4 5]]
Transposed Array
[[0 3]
 [1 4]
 [2 5]]

We have defined an array using the np arange function and reshaped it to (2 X 3).

Then we have used the transpose() function to change the rows into columns and columns into rows.

Transpose two-dimensional array (matrix)

You can get a transposed matrix of the original two-dimensional array (matrix) with the T attribute in Python. See the following code.

import numpy as np

arr2d = np.arange(6).reshape(2, 3)
print(arr2d)
print('\n')
print('After using T attribute: ')
arr2d_T = arr2d.T
print(arr2d_T)

Output

[[0 1 2]
 [3 4 5]]


After using T attribute:
[[0 3]
 [1 4]
 [2 5]]

The Numpy T attribute returns the view of the original array, and changing one changes the other. You can check if the ndarray refers to data in the same memory with np.shares_memory().

ndarray.transpose()

The transpose() is provided as a method of ndarray. Like, T, the view is returned.

import numpy as np

arr2d = np.arange(6).reshape(2, 3)
print(arr2d)
print('\n')
print('After using transpose() function: ')
arr2d_T = arr2d.transpose()
print(arr2d_T)

Output

[[0 1 2]
 [3 4 5]]


After using transpose() function:
[[0 3]
 [1 4]
 [2 5]]

You can see that we got the same output as above. 

Transpose of an Array Like Object

The transpose() function works with an array-like object, such as a nested list.

# app.py

import numpy as np

arr = [[11, 21, 19], [46, 18, 29]]
print(arr)

arr1_transpose = np.transpose(arr)
print(arr1_transpose)

Output

python3 app.py
[[11, 21, 19], [46, 18, 29]]
[[11 46]
 [21 18]
 [19 29]]

Convert 1D vector to a 2D array in Numpy

If you want to convert your 1D vector into the 2D array and then transpose it, slice it with numpy np.newaxis (or None, they are the same; the new axis is only more readable).

See the following code.

# app.py

import numpy as np

arr = np.array([19, 21])[np.newaxis]
print(arr)
print(arr.T)

Output

python3 app.py
[[19 21]]
[[19]
 [21]]

Adding the extra dimension is usually not what you need if you do it out of habit.

Numpy will automatically broadcast the 1D array when doing various calculations. So there’s usually no need to distinguish between the row vector and the column vector (neither of which are vectors. They are both 2D!) when you want the vector.

You can also use the following method.

# app.py

import numpy as np

arr = np.array([19, 21, 29, 46])
rearr = arr.reshape((-1, 1))
print(rearr)

Output

python3 app.py
[[19]
 [21]
 [29]
 [46]]

Use transpose(arr, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument. For example, transposing the 1D array returns the unchanged view of the original array.

Applying transpose() or T to a one-dimensional array

If we apply T or transpose() to a one-dimensional array, then it returns an array equivalent to the original array.

import numpy as np

arr2d = np.arange(6)
print(arr2d)
print('\n')
print('After applying T: ')
arr2d_T = arr2d.T
print(arr2d_T)
print('\n')
print('After applying transpose() function: ')
arr2d_transpose = arr2d.transpose()
print(arr2d_transpose)

Output

[0 1 2 3 4 5]


After applying T:
[0 1 2 3 4 5]


After applying transpose() function:
[0 1 2 3 4 5]

You can see in the output that, After applying the T or transpose() function to a 1D array, it returns an original array.

Numpy matrix.transpose()

In the above section, we have seen how to find numpy array transpose using the numpy transpose() function. But, first, let’s find the transpose of the numpy matrix().

# app.py

import numpy as np

mat = np.matrix('[19, 21; 11, 10]')
print("Original Matrix")
print(mat)

# applying matrix.transpose() method
print('Transposed Matrix')
print(mat.transpose())

Output

python3 app.py
Original Matrix
[[19 21]
 [11 10]]
Transposed Matrix
[[19 11]
 [21 10]]

A matrix with only one row is called the row vector, and a matrix with one column is called the column vector, but there is no distinction between rows and columns in the one-dimensional array of ndarray.

A two-dimensional array indicates that only rows or columns are present.

Here, transform the shape by using reshape().

Specifying axis order with transpose()

Using T permanently reverses the order, but you can specify any order using the transpose() method.

In the below example, specify the same reversed order as the default, and confirm that the result does not change.

The ndarray method transpose() specifies an axis order with variable length arguments or tuples.

import numpy as np

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

print(arr.transpose(2, 1, 0))

Output

[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
[[[ 0 12]
  [ 4 16]
  [ 8 20]]

 [[ 1 13]
  [ 5 17]
  [ 9 21]]

 [[ 2 14]
  [ 6 18]
  [10 22]]

 [[ 3 15]
  [ 7 19]
  [11 23]]]

An error occurs if the number of specified axes does not match several dimensions of an original array or if the dimension that does not exist is specified.

Conclusion

In this Numpy transpose tutorial, we have seen how to use the transpose() function on numpy array and numpy matrix, the difference between numpy matrix and array, and convert 1D to the 2D array.

That’s it.

See also

Numpy array shape

Numpy array attributes

How to find Numpy array index

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.