NumPy ndarray.T Attribute



The NumPy ndarray.T attribute is used to get the transpose of a NumPy array. Transposing an array means swapping its rows and columns, which is a common operation in linear algebra and matrix manipulation.

The T attribute provides a simple way to access the transposed version of an array without needing to use any function calls.

Transposing is useful when you need to rotate, reflect, or reshape the array for various mathematical operations.

Usage of the T Attribute in NumPy

The T attribute can be accessed directly from a NumPy array object to obtain its transpose.

It is commonly used when you need to switch the rows and columns of a 2D array or to change the shape of higher-dimensional arrays.

Below are some examples that demonstrate how T can be applied to various arrays in NumPy.

Example: Basic Usage of T Attribute

In this example, we create a simple 2-dimensional array and use the T attribute to transpose the array −

import numpy as np

# Creating a 2-dimensional array
arr = np.array([[1, 2], [3, 4]])
print(arr.T)

Following is the output obtained −

[[1 3]
 [2 4]]

Example: Transposing a Higher Dimensional Array

In this example, we create a 3-dimensional array and use the T attribute to transpose the array −

import numpy as np

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

This will produce the following result −

[[[1 5]
  [3 7]]

 [[2 6]
  [4 8]]]

Example: Transposing a 1D Array

In this example, we use the T attribute on a 1-dimensional array. The transpose of a 1D array is simply the array itself, as it has only one dimension −

import numpy as np

# Creating a 1-dimensional array
arr = np.array([1, 2, 3, 4])
print(arr.T)

Following is the output obtained −

[1 2 3 4]

Example: Transposing an Empty Array

In this example, we check the result of transposing an empty array using the T attribute −

import numpy as np

# Creating an empty array
arr = np.array([])
print(arr.T)

The output obtained is as shown below −

[]
numpy_array_attributes.htm
Advertisements