Numpy Array Manipulation

.Transpose Operations

transpose

This function permutes the dimension of the given array.
It returns a view wherever possible.

Syntax
transpose(arr, axes=None)
Parameter
arr: Input array.
axes: By default, reverse the dimensions, otherwise permute the axes according to the values given.

>>> d=np.array([[1,5,3],[2,5,6]])
>>> d
array([[1, 5, 3],
       [2, 5, 6]])

>>> np.transpose(d,axes=[1,0])
array([[1, 2],
       [5, 5],
       [3, 6]])

>>> np.transpose(d,axes=[0,1])
array([[1, 5, 3],
       [2, 5, 6]])

rollaxis

This function rolls the specified axis backwards until it lies in a specified position.

This function continues to be supported for backward compatibility.

numpy.rollaxis(arr, axis, start)

arr-input array
axis-Axis to roll backwards. The position of the other axes do not change relative to one another.
start-Zero by default leading to the complete roll. Rolls until it reaches the specified position

>>> a = np.ones((3,4,5,6))

>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)

>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)

>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)

swapaxes

This function interchanges the two axes of an array.

numpy.swapaxes(arr, axis1, axis2)

arr: Input array whose axes are to be swapped
axis1: An int corresponding to the first axis
axis2:  An int corresponding to the second axis

>>>a=np.array([[1.5,2,3],[4,5,6]])
>>> a
array([[1.5, 2. , 3. ],
       [4. , 5. , 6. ]])

>>> np.swapaxes(a,0,1)
array([[1.5, 4. ],
       [2. , 5. ],
       [3. , 6. ]])

>>> a=np.array([[[1.5,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
>>> a
array([[[ 1.5,  2. ,  3. ],
        [ 4. ,  5. ,  6. ]],
        [[ 7. ,  8. ,  9. ],
        [10. , 11. , 12. ]]])

>>>np.swapaxes(a,2,0)
array([[[ 1.5,  7. ],
        [ 4. , 10. ]],

       [[ 2. ,  8. ],
        [ 5. , 11. ]],

       [[ 3. ,  9. ],
        [ 6. , 12. ]]])

moveaxis

Move axes of an array to new positions.

Other axes remain in their original order.

numpy.moveaxis(arr, source, destination)

arr: The array whose axes should be reordered.
source:  Original positions of the axes to move.
destination: Destination positions for each of the original axes.

>>> x = np.zeros((3, 4, 5))

>>> np.moveaxis(x, 0, -1).shape
(4, 5, 3)

>>> np.moveaxis(x, -1, 0).shape
(5, 3, 4)

ndarray.T

It is similar to numpy.transpose

This function below to ndarray class.
self is returned if self.ndim < 2

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

>>> x.T
array([[1, 3],
       [2, 4]])

You May Also Like

About the Author: Nitesh

I am a software engineer and Enthusiastic to learn new things

Leave a Reply

Your email address will not be published. Required fields are marked *