NumPy ndarray.transpose()

The numpy.ndarray.transpose() method returns a view of the array with axes permuted according to the specified order. If no axes are provided, it reverses the order of axes.

Syntax

</>
Copy
ndarray.transpose(*axes)

Parameters

ParameterTypeDescription
*axestuple of ints, or n ints, optionalBy default, the axes are reversed. If provided, it specifies a permutation of the axes.

Return Value

Returns a new view of the array with the specified permutation of axes.


Examples

1. Transposing a 2D Array

In this example, we transpose a 2D array, swapping rows and columns.

</>
Copy
import numpy as np

# Creating a 2D array
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

# Transposing the array (rows become columns and vice versa)
transposed_arr = arr.transpose()

print("Original Array:")
print(arr)

print("\nTransposed Array:")
print(transposed_arr)

Output:

Original Array:
[[1 2 3]
 [4 5 6]]

Transposed Array:
[[1 4]
 [2 5]
 [3 6]]

2. Transposing a 3D Array

Here, we transpose a 3D array, modifying the order of its axes.

</>
Copy
import numpy as np

# Creating a 3D array
arr = np.array([[[1, 2], [3, 4]],
                [[5, 6], [7, 8]]])

# Transposing the array by swapping axes
transposed_arr = arr.transpose(1, 0, 2)  

print("Original Array Shape:", arr.shape)
print("Transposed Array Shape:", transposed_arr.shape)

print("\nOriginal Array:")
print(arr)

print("\nTransposed Array:")
print(transposed_arr)

Output:

Original Array Shape: (2, 2, 2)
Transposed Array Shape: (2, 2, 2)

Original Array:
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

Transposed Array:
[[[1 2]
  [5 6]]

 [[3 4]
  [7 8]]]

3. Reversing the Axes of a 3D Array

If no arguments are provided, transpose() reverses the axes of the array.

</>
Copy
import numpy as np

# Creating a 3D array
arr = np.array([[[1, 2, 3], 
                 [4, 5, 6]],

                [[7, 8, 9], 
                 [10, 11, 12]]])

# Transposing without arguments (reverses the axes)
transposed_arr = arr.transpose()

print("Original Shape:", arr.shape)
print("Transposed Shape:", transposed_arr.shape)

print("\nOriginal Array:")
print(arr)

print("\nTransposed Array:")
print(transposed_arr)

Output:

Original Shape: (2, 2, 3)
Transposed Shape: (3, 2, 2)

Original Array:
[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]

Transposed Array:
[[[ 1  7]
  [ 4 10]]

 [[ 2  8]
  [ 5 11]]

 [[ 3  9]
  [ 6 12]]]

4. Transposing a 1D Array

Transposing a 1D array has no effect, as it has only one axis.

</>
Copy
import numpy as np

# Creating a 1D array
arr = np.array([1, 2, 3, 4, 5])

# Attempting to transpose a 1D array
transposed_arr = arr.transpose()

print("Original Array:", arr)
print("Transposed Array:", transposed_arr)

Output:

Original Array: [1 2 3 4 5]
Transposed Array: [1 2 3 4 5]

Since a 1D array has only one axis, transposing it does not change its structure.