Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy ndarray.T Attribute



The Numpy ndarray.T Attribute is used to return the transpose of an array which is essentially an array with its axes permuted.

For a 2-D array it swaps the rows and columns. It does not create a new array but rather returns a view of the original array with its dimensions changed.

This operation is especially useful for linear algebra computations and data manipulation tasks.

Syntax

The syntax for the Numpy ndarray.T Attribute is as follows −

ndarray.T

Parameter

This attribute does not take any parameters.

Return Value

The ndarray.T attribute returns a new array which is the transpose of the original array.

Example 1

Following is the example which shows the basic usage of Numpy ndarray.T Attribute to transpose a 2D matrix by swapping its rows and columns.

import numpy as np

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

# Transposing the matrix
transposed_matrix = matrix.T

print("Original Matrix:")
print(matrix)
print("Transposed Matrix:")
print(transposed_matrix)

Output

Original Matrix:
[[1 2]
 [3 4]]
Transposed Matrix:
[[1 3]
 [2 4]]

Example 2

In this example we show how the ndarray.T attribute works on a 3D array by swapping the first and third axes.

import numpy as np

# Creating a 3D array
array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

# Transposing the 3D array
transposed_3d = array_3d.T

print("Original 3D Array:")
print(array_3d)
print("Transposed 3D Array:")
print(transposed_3d)

Output

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

 [[ 7  8  9]
  [10 11 12]]]
Transposed 3D Array:
[[[ 1  7]
  [ 4 10]]

 [[ 2  8]
  [ 5 11]]

 [[ 3  9]
  [ 6 12]]]

Example 3

Here in this example the ndarray.T attribute changes the axes of the array effectively swapping rows and columns for 2D arrays.

import numpy as np 

# Create a 3x4 array
a = np.arange(12).reshape(3, 4) 

print('The original array is:') 
print(a)  
print('\n') 

print('The transposed array is:') 
print(np.transpose(a))

Output

The original array is:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


The transposed array is:
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]
numpy_array_manipulation.htm
Advertisements