English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Common array flip methods and other methods
Function | Description |
transpose | Swap the dimensions of the array |
ndarray.T | Same as self.transpose() |
rollaxis | Roll the specified axis |
swapaxes | Swap two axes of the array |
The numpy.transpose function is used to swap the dimensions of an array, with the format as follows:
numpy.transpose(arr, axes)
Parameter Description:
arr: The array to be operated onaxes: List of integers, corresponding to dimensions, usually all dimensions will be swapped.
import numpy as np a = np.arange(12).reshape(3,4) print ('Original array:') print (a ) print ('\n') print ('Swap array:') print (np.transpose(a))
The output is as follows:
Original array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Swap array: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
The numpy.ndarray.T is similar to numpy.transpose:
import numpy as np a = np.arange(12).reshape(3,4) print ('Original array:') print (a) print ('\n') print ('Transpose array:') print (a.T)
The output is as follows:
Original array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Transpose array: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
The numpy.rollaxis function rolls a specific axis to a specific position, with the format as follows:
numpy.rollaxis(arr, axis, start)
Parameter Description:
arr: Arrayaxis: The axis to roll back, the relative positions of other axes will not changestart: Default is zero, indicating a full roll. It will roll to a specific position.
import numpy as np # Created a three-dimensional ndarray a = np.arange(8).reshape(2,2,2) print ('Original array:') print (a) print ('\n') # Roll axis 2 Roll axis 0 (width to depth) print ('Calling the rollaxis function:') print (np.rollaxis(a,2)) # Roll axis 0 to axis 1(Width to height) print ('\n') print ('Calling the rollaxis function:') print (np.rollaxis(a,2,1))
The output is as follows:
Original array: [[[0 1] [2 3]] [[4 5] [6 7]]] Calling the rollaxis function: [[[0 2] [4 6]] [[1 3] [5 7]]] Calling the rollaxis function: [[[0 2] [1 3]] [[4 6] [5 7]]]
The numpy.swapaxes function is used to swap two axes of an array, the format is as follows:
numpy.swapaxes(arr, axis1, axis2)
arr: Input arrayaxis1: Integer corresponding to the first axisaxis2: Integer corresponding to the second axis
import numpy as np # Created a three-dimensional ndarray a = np.arange(8).reshape(2,2,2) print ('Original array:') print (a) print ('\n') # Now swap axis 0 (depth direction) to axis 2(Width direction) print ('The array after calling the swapaxes function:') print (np.swapaxes(a, 2, 0))
The output is as follows:
Original array: [[[0 1] [2 3]] [[4 5] [6 7]]] The array after calling the swapaxes function: [[[0 4] [2 6]] [[1 5] [3 7]]]