What is Array Transposition?

By transposing an array in NumPy, we mean rearranging its dimensions to access its data along different axes:

  • For a 2D Array (Matrix): Transposing flips the matrix across its main diagonal, effectively swapping rows and columns. An array with shape (m, n) becomes (n, m), where the element at (i, j) moves to (j, i).
  • For Multidimensional Arrays (≥ 3D): Transposing involves permuting the order of the axes according to a specified sequence.

NumPy returns a view of the original array whenever possible without copying data, making transpositions virtually instantaneous.

1. Transposing Arrays Using numpy.transpose()

The transpose() function in NumPy rearranges the dimensions of an array. If the order of axes is not specified, NumPy reverses the dimensions completely.

Syntax

numpy.transpose(a, axes=None)
Parameter Description
a The input array-like object to be transposed.
axes (optional) Tuple or list of ints specifying the new order of axes. If omitted (or None), it defaults to completely reversing the dimensions (e.g. (0, 1, 2) → (2, 1, 0)).

Example 1: Transposing a 2D Array (Rows ↔ Columns)

Here, a (2, 3) array is transposed into a (3, 2) array, converting rows into columns:

import numpy as np # 2D array of shape (2, 3) arr = np.array([[1, 2, 3], [4, 5, 6]]) # Transposing the array transposed_arr = np.transpose(arr) print("Original Array (2x3):") print(arr) print("\nTransposed Array (3x2):") print(transposed_arr) print("\nNew Shape:", transposed_arr.shape)

Output:

Original Array (2x3): [[1 2 3] [4 5 6]] Transposed Array (3x2): [[1 4] [2 5] [3 6]] New Shape: (3, 2)
Visual Breakdown
Row 0: [1, 2, 3] → Column 0: [[1], [2], [3]] Row 1: [4, 5, 6] → Column 1: [[4], [5], [6]] Result: [[1, 4], [2, 5], [3, 6]]

2. Transposing 3D Arrays

When transposing a 3D array without specifying axes, NumPy reverses all dimensions: axis 0 becomes axis 2, and axis 2 becomes axis 0.

Example: Transposing a 3D Array with Default Reversal

import numpy as np # 3D array of shape (2, 2, 2) arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Transpose 3D array (reverses axes: 0, 1, 2 -> 2, 1, 0) transposed_arr_3d = np.transpose(arr_3d) print("Original 3D Array:") print(arr_3d) print("\nTransposed 3D Array:") print(transposed_arr_3d)

Output:

Original 3D Array: [[[1 2] [3 4]] [[5 6] [7 8]]] Transposed 3D Array: [[[1 5] [3 7]] [[2 6] [4 8]]]

3. Transposing with Specified Axes (Permutation)

In machine learning and computer vision (e.g. converting PyTorch (Channels, Height, Width) to TensorFlow (Height, Width, Channels)), you often need to permute specific axes while leaving others untouched.

You can achieve this by passing a tuple of axis indices to the axes parameter.

Example: Swapping Axes 1 and 2 While Keeping Axis 0

In this example, we keep the first dimension (axis 0) unchanged and swap axes 1 and 2 by setting axes=(0, 2, 1):

import numpy as np # 3D array of shape (2, 2, 2) arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Transpose: Keep axis 0, swap axis 1 and axis 2 transposed_arr = np.transpose(arr, axes=(0, 2, 1)) print("Original 3D Array:") print(arr) print("\nTransposed 3D Array (axes=(0, 2, 1)):") print(transposed_arr)

Output:

Original 3D Array: [[[1 2] [3 4]] [[5 6] [7 8]]] Transposed 3D Array (axes=(0, 2, 1)): [[[1 3] [2 4]] [[5 7] [6 8]]]

4. Transposing Arrays Using the .T Attribute

NumPy arrays provide a convenient shorthand attribute: ndarray.T. It provides an instant way to transpose arrays without writing np.transpose().

Example: Quick Transposition via .T

import numpy as np # Creating a 2D array arr = np.array([[1, 2, 3], [4, 5, 6]]) # Transpose using the .T attribute transposed_arr = arr.T print("Original Array:") print(arr) print("\nTransposed Array using .T:") print(transposed_arr)

Output:

Original Array: [[1 2 3] [4 5 6]] Transposed Array using .T: [[1 4] [2 5] [3 6]]
Common NumPy Gotcha: 1D Arrays and .T

Calling .T on a 1-dimensional array does not change its shape:

a = np.array([1, 2, 3])
print(a.shape) # (3,)
print(a.T.shape) # (3,) — Still 1D!

Because a 1D array has only one axis, reversing (0,) still gives (0,). If you need a 2D column vector, use a.reshape(-1, 1) or a[:, np.newaxis].


5. Summary: np.transpose() vs .T

Feature np.transpose(arr, axes) arr.T
Type NumPy module function ndarray property attribute
Axis Reordering Supports arbitrary custom axis permutation via axes=(...) Always reverses all axes
Memory View Returns a view (no memory allocation) Returns a view (no memory allocation)
Best For Complex multidimensional tensor axis swapping Quick 2D matrix transposition

Array Transposition Quiz

Test your understanding of array transposition in NumPy. Click an option to see instant feedback.

1. If array A has shape (3, 5), what is the shape of A.T?
A) (3, 5)
B) (5, 3)
C) (15,)
D) (1, 15)
2. What happens if you call .T on a 1D array of shape (6,)?
A) It converts to shape (6, 1)
B) It converts to shape (1, 6)
C) Its shape remains unchanged at (6,)
D) It raises a ValueError
3. Does arr.T create a copy of the data in memory?
A) Yes, it always creates a deep copy
B) No, it returns a view by modifying the array's strides and shape
C) Yes, but only for 3D arrays
D) Only if order='F' is specified
4. If an image array has shape (100, 200, 3) representing (Height, Width, Channels), which transposition converts it to (3, 100, 200)?
A) np.transpose(img, (2, 0, 1))
B) np.transpose(img, (0, 2, 1))
C) img.T
D) np.transpose(img, (1, 2, 0))
5. If element 7 is at position arr[1, 3], where will it be in arr.T?
A) arr.T[1, 3]
B) arr.T[3, 1]
C) arr.T[2, 2]
D) arr.T[0, 0]