numpy
  1. numpy-numpytranspose

numpy.transpose()

The numpy.transpose() function is used to permute the dimensions of an array. This function alters the shape and size of the array, and returns a new array with the modified dimensions.

Syntax

numpy.transpose(arr, axes=None)

Here, arr parameter represents the array to be transposed, and axes parameter represents the order of the axes transpose of the array. If the axes parameter is not specified, the function will reverse the order of the dimensions of the array.

Example

import numpy as np

x = np.array([[1, 2], [3, 4]])
y = np.transpose(x)

print("Original array:\n", x)
print("Transposed array:\n", y)

Output:

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

In this example, we have an array x with dimensions 2x2. We pass this array to numpy.transpose() function, which returns the transposed array y. The dimensions of the transposed array are now 2x2, but the order of elements has been swapped across the two axes.

Explanation

The numpy.transpose() function is used to permute the dimensions of an array. The permutation can be specified explicitly using the axes parameter or left defaulted to the reverse order of the dimensions.

If the input array has dimensions n x m, the transpose operation on it would create a new array with dimensions m x n. The elements in the resulting array are obtained by swapping the positions of the elements in the original array along the axes.

Use

The numpy.transpose() function can be used to change the shape and size of an array. This function is useful in data analysis when the dimensions of the output need to be changed to match a different set of input expectation. It is useful when there is a need to change a two-dimensional array to a one-dimensional array with the same elements in a different order.

Important Points

  • The numpy.transpose() function treats one-dimensional arrays as row or column arrays depending on the parameters specified.
  • If the axes parameter is not provided explicitly, then it defaults to the reverse order of dimensions.
  • The numpy.transpose() function returns a new array; it does not modify the original array.

Summary

The numpy.transpose() function is used to transpose an array by swapping the positions of elements along a specified number of axes. This function is useful in data analysis and is used primarily for changing the shape and size of the array. The function returns a new array and does not modify the original array.

Published on: