NumPy ndarray.T Attribute

The ndarray.T attribute in NumPy provides a view of the transposed array. It swaps the array’s axes, effectively flipping rows into columns and vice versa.

Syntax

</>
Copy
ndarray.T

Return Value

Returns a view of the transposed array where rows become columns and columns become rows. The number of dimensions remains the same.


Examples

1. Transposing a 2D NumPy Array

In this example, we create a 2D NumPy array and obtain its transposed view.

</>
Copy
import numpy as np  

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

# Transposing the array using .T attribute
transposed = arr.T

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

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

Output:

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

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

The original array has a shape of (2,3), and after transposition, it changes to (3,2), swapping rows with columns.

2. Transposing a 1D NumPy Array

Transposing a 1D array does not change its shape as it has only one dimension.

</>
Copy
import numpy as np  

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

# Transposing the 1D array
transposed = arr.T

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

Output:

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

The shape remains unchanged since a 1D array does not have a second axis to swap.

3. Transposing a 3D NumPy Array

For multidimensional arrays, .T swaps the first and last axes while keeping the middle axis unchanged.

</>
Copy
import numpy as np  

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

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

# Transposing the 3D array
transposed = arr.T

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

Output:

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

The transposition swaps the first and last axes, but does not flatten the structure.