NumPy: Transpose ndarray (swap rows and columns, rearrange axes)

Posted: | Tags: Python, NumPy

To transpose NumPy array ndarray (swap rows and columns), use the T attribute (.T), the ndarray method transpose() and the numpy.transpose() function.

With ndarray.transpose() and numpy.transpose(), you can not only transpose a 2D array (matrix) but also rearrange the axes of a multi-dimensional array in any order.

This article describes the following contents.

  • Transpose two-dimensional array (matrix)
    • T attribute
    • ndarray.transpose()
    • np.transpose()
  • 1D array and row vector, column vector
  • Swap axes of multi-dimensional array (3D or higher)
    • Default result
    • Specify axis order with transpose()
    • Example: Transpose multiple matrices at once

If you want to swap rows and columns of pandas.DataFrame or a two-dimensional list (list of lists), see the following article.

Transpose two-dimensional array (matrix)

T attribute

You can get the transposed matrix of the original two-dimensional array (matrix) with the T attribute.

import numpy as np

a_2d = np.arange(6).reshape(2, 3)
print(a_2d)
# [[0 1 2]
#  [3 4 5]]

a_2d_T = a_2d.T
print(a_2d_T)
# [[0 3]
#  [1 4]
#  [2 5]]

The T attribute returns a view of the original array, and changing one changes the other.

You can check if ndarray refers to data in the same memory with np.shares_memory().

print(np.shares_memory(a_2d, a_2d_T))
# True

a_2d_T[0, 1] = 100
print(a_2d_T)
# [[  0 100]
#  [  1   4]
#  [  2   5]]

print(a_2d)
# [[  0   1   2]
#  [100   4   5]]

a_2d[1, 0] = 3
print(a_2d)
# [[0 1 2]
#  [3 4 5]]

print(a_2d_T)
# [[0 3]
#  [1 4]
#  [2 5]]

If you want to process it as separate data, make a copy with copy().

a_2d_T_copy = a_2d.T.copy()
print(a_2d_T_copy)
# [[0 3]
#  [1 4]
#  [2 5]]

print(np.shares_memory(a_2d, a_2d_T_copy))
# False

a_2d_T_copy[0, 1] = 100
print(a_2d_T_copy)
# [[  0 100]
#  [  1   4]
#  [  2   5]]

print(a_2d)
# [[0 1 2]
#  [3 4 5]]

ndarray.transpose()

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

print(a_2d.transpose())
# [[0 3]
#  [1 4]
#  [2 5]]

print(np.shares_memory(a_2d, a_2d.transpose()))
# True

np.transpose()

numpy.transpose() function is also provided. Specify the original array to the first argument. This also returns a view.

print(np.transpose(a_2d))
# [[0 3]
#  [1 4]
#  [2 5]]

print(np.shares_memory(a_2d, np.transpose(a_2d)))
# True

1D array and row vector, column vector

Applying T or transpose() to a one-dimensional array only returns an array equivalent to the original array.

a_1d = np.arange(3)
print(a_1d)
# [0 1 2]

print(a_1d.T)
# [0 1 2]

print(a_1d.transpose())
# [0 1 2]

print(np.transpose(a_1d))
# [0 1 2]

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

A two-dimensional array is used to indicate clearly that only rows or columns are present.

Here, transform the shape by using reshape().

a_row = a_1d.reshape(1, -1)
print(a_row)
# [[0 1 2]]

print(a_row.shape)
# (1, 3)

print(a_row.ndim)
# 2
a_col = a_1d.reshape(-1, 1)
print(a_col)
# [[0]
#  [1]
#  [2]]

print(a_col.shape)
# (3, 1)

print(a_col.ndim)
# 2

As mentioned above, two-dimensional arrays can be transposed.

print(a_row.T)
# [[0]
#  [1]
#  [2]]

print(a_col.T)
# [[0 1 2]]

Note that the result differs whether using one-dimensional or two-dimensional arrays when performing matrix multiplication with dot(), matmul(), or the @ operator. Refer to the following article for details.

There is a difference in the concatenation of arrays: vstack() can concatenate a two-dimensional array and a one-dimensional array, while hstack() cannot. Two-dimensional arrays can be concatenated in either case. For more details, see the following article.

Swap axes of multi-dimensional array (3D or higher)

Default result

T, transpose() can be applied to multi-dimensional arrays of 3D or higher.

The default result is as follows. np.transpose() has the same result.

a_3d = np.arange(24).reshape(2, 3, 4)
print(a_3d)
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
# 
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]

print(a_3d.T)
# [[[ 0 12]
#   [ 4 16]
#   [ 8 20]]
# 
#  [[ 1 13]
#   [ 5 17]
#   [ 9 21]]
# 
#  [[ 2 14]
#   [ 6 18]
#   [10 22]]
# 
#  [[ 3 15]
#   [ 7 19]
#   [11 23]]]

print(a_3d.T.shape)
# (4, 3, 2)

print(a_3d.transpose())
# [[[ 0 12]
#   [ 4 16]
#   [ 8 20]]
# 
#  [[ 1 13]
#   [ 5 17]
#   [ 9 21]]
# 
#  [[ 2 14]
#   [ 6 18]
#   [10 22]]
# 
#  [[ 3 15]
#   [ 7 19]
#   [11 23]]]

print(a_3d.transpose().shape)
# (4, 3, 2)

It is difficult to understand just by looking at the output result, but the order of the axis (dimension) of (0th axis, 1st axis, 2nd axis) is reversed like (2nd axis, 1st axis, 0th axis ).

In a 2D array, the order of (0th axis, 1st axis) = (row, column) is changed to the order of (1st axis, 0th axis) = (column, row).

Specify axis order with transpose()

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

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

In the ndarray method transpose(), specify the axis order with variable length arguments or tuple.

print(a_3d.transpose(2, 1, 0))
# [[[ 0 12]
#   [ 4 16]
#   [ 8 20]]
# 
#  [[ 1 13]
#   [ 5 17]
#   [ 9 21]]
# 
#  [[ 2 14]
#   [ 6 18]
#   [10 22]]
# 
#  [[ 3 15]
#   [ 7 19]
#   [11 23]]]

print(a_3d.transpose(2, 1, 0).shape)
# (4, 3, 2)

print(a_3d.transpose((2, 1, 0)).shape)
# (4, 3, 2)

In np.transpose(), specify the order as the second argument with tuple. It cannot be specified with variable length arguments.

print(np.transpose(a_3d, (2, 1, 0)))
# [[[ 0 12]
#   [ 4 16]
#   [ 8 20]]
# 
#  [[ 1 13]
#   [ 5 17]
#   [ 9 21]]
# 
#  [[ 2 14]
#   [ 6 18]
#   [10 22]]
# 
#  [[ 3 15]
#   [ 7 19]
#   [11 23]]]

print(np.transpose(a_3d, (2, 1, 0)).shape)
# (4, 3, 2)

# print(np.transpose(a_3d, 2, 1, 0))
# TypeError: transpose() takes from 1 to 2 positional arguments but 4 were given

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

# print(a_3d.transpose(0, 1))
# ValueError: axes don't match array

# print(a_3d.transpose(0, 1, 2, 3))
# ValueError: axes don't match array

# print(a_3d.transpose(0, 1, 3))
# AxisError: axis 3 is out of bounds for array of dimension 3

Example: Transpose multiple matrices at once

For example, transpose() is useful when a 3D array is a group of 2D arrays.

If the data of matrices are stored as a 3D array of shape (n, row, column), all matrices can be transposed as follows.

print(a_3d)
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
# 
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]

print(a_3d.shape)
# (2, 3, 4)

print(a_3d.transpose(0, 2, 1))
# [[[ 0  4  8]
#   [ 1  5  9]
#   [ 2  6 10]
#   [ 3  7 11]]
# 
#  [[12 16 20]
#   [13 17 21]
#   [14 18 22]
#   [15 19 23]]]

print(a_3d.transpose(0, 2, 1).shape)
# (2, 4, 3)

If the shape is (row, column, n), you can do as follows.

print(a_3d.transpose(1, 0, 2))
# [[[ 0  1  2  3]
#   [12 13 14 15]]
# 
#  [[ 4  5  6  7]
#   [16 17 18 19]]
# 
#  [[ 8  9 10 11]
#   [20 21 22 23]]]

print(a_3d.transpose(1, 0, 2).shape)
# (3, 2, 4)

print(a_3d[:, :, 0])
# [[ 0  4  8]
#  [12 16 20]]

print(a_3d.transpose(1, 0, 2)[:, :, 0])
# [[ 0 12]
#  [ 4 16]
#  [ 8 20]]

Related Categories

Related Articles