NumPy 数组翻转
NumPy 数组翻转的一些操作
常见的数组翻转等方法
函数 |
描述 |
transpose |
对换数组的维度 |
ndarray.T |
和 self.transpose() 相同 |
rollaxis |
向后滚动指定的轴 |
swapaxes |
对换数组的两个轴 |
numpy.transpose
numpy.transpose 函数用于对换数组的维度,格式如下:
numpy.transpose(arr, axes)
参数说明:
arr
:要操作的数组
axes
:整数列表,对应维度,通常所有维度都会对换。
import numpy as np
a = np.arange(12).reshape(3,4)
print ('原数组:')
print (a )
print ('\n')
print ('对换数组:')
print (np.transpose(a))
输出结果如下:
原数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
对换数组:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
numpy.ndarray.T 类似 numpy.transpose:
import numpy as np
a = np.arange(12).reshape(3,4)
print ('原数组:')
print (a)
print ('\n')
print ('转置数组:')
print (a.T)
输出结果如下:
原数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
转置数组:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
numpy.rollaxis
numpy.rollaxis 函数向后滚动特定的轴到一个特定位置,格式如下:
numpy.rollaxis(arr, axis, start)
参数说明:
arr
:数组
axis
:要向后滚动的轴,其它轴的相对位置不会改变
start
:默认为零,表示完整的滚动。会滚动到特定位置。
import numpy as np
# 创建了三维的 ndarray
a = np.arange(8).reshape(2,2,2)
print ('原数组:')
print (a)
print ('\n')
# 将轴 2 滚动到轴 0(宽度到深度)
print ('调用 rollaxis 函数:')
print (np.rollaxis(a,2))
# 将轴 0 滚动到轴 1:(宽度到高度)
print ('\n')
print ('调用 rollaxis 函数:')
print (np.rollaxis(a,2,1))
输出结果如下:
原数组:
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
调用 rollaxis 函数:
[[[0 2]
[4 6]]
[[1 3]
[5 7]]]
调用 rollaxis 函数:
[[[0 2]
[1 3]]
[[4 6]
[5 7]]]
numpy.swapaxes
numpy.swapaxes 函数用于交换数组的两个轴,格式如下:
numpy.swapaxes(arr, axis1, axis2)
arr
:输入的数组
axis1
:对应第一个轴的整数
axis2
:对应第二个轴的整数
import numpy as np
# 创建了三维的 ndarray
a = np.arange(8).reshape(2,2,2)
print ('原数组:')
print (a)
print ('\n')
# 现在交换轴 0(深度方向)到轴 2(宽度方向)
print ('调用 swapaxes 函数后的数组:')
print (np.swapaxes(a, 2, 0))
输出结果如下:
原数组:
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
调用 swapaxes 函数后的数组:
[[[0 4]
[2 6]]
[[1 5]
[3 7]]]