numpy学习专题
十一、numpy翻转数组
翻转数组
transpose()
原型:numpy.transpose(a,axes =None)
作用:对换数组的维度
注意:修改会影响原始数组
参数 说明
a 要操作的数组
axes 整数列表,对应维度,通常所有维度都会对换
import numpy as np
arr = np.arange(24).reshape(4,3,2)
arr2 =np.transpose(arr)
print("arr:\n",arr,"\n")
print("arr.shape",arr.shape,"\n")
print("arr2\n",arr2,"\n")
print("arr2.shape",arr2.shape,"\n")
arr:
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]
[[12 13]
[14 15]
[16 17]]
[[18 19]
[20 21]
[22 23]]]
arr.shape (4, 3, 2)
arr2
[[[ 0 6 12 18]
[ 2 8 14 20]
[ 4 10 16 22]]
[[ 1 7 13 19]
[ 3 9 15 21]
[ 5 11 17 23]]]
arr2.shape (2, 3, 4)
import numpy as np
arr = np.arange(24).reshape(4,6)
arr2 =arr.T
print("arr:\n",arr,"\n")
print("arr.shape",arr.shape,"\n")
print("arr2\n",arr2,"\n")
print("arr2.shape",arr2.shape,"\n")
arr:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]
arr.shape (4, 6)
arr2
[[ 0 6 12 18]
[ 1 7 13 19]
[ 2 8 14 20]
[ 3 9 15 21]
[ 4 10 16 22]
[ 5 11 17 23]]
arr2.shape (6, 4)
rollaxis
原型:numpy.rollaxis(a,axis,start=0)
作用:向后滚动特定的轴到一个特定的位置
参数 说明
a 要操作的数组
axis 要向后滚动的轴,其他轴的相对位置不会改变
start 默认为零,表示完整的滚动,否则会滚动到特定的位置
import numpy as np
arr = np.arange(24).reshape(4,2,3)
print("arr:\n",arr,"\n")
print("\n",arr.shape,"\n")
arr2 = np.rollaxis(arr,2)
print("arr:\n",arr2,"\n")
print("\n",arr2.shape,"\n")
arr:
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]
[[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]]]
(4, 2, 3)
arr:
[[[ 0 3]
[ 6 9]
[12 15]
[18 21]]
[[ 1 4]
[ 7 10]
[13 16]
[19 22]]
[[ 2 5]
[ 8 11]
[14 17]
[20 23]]]
(3, 4, 2)
swapaxes()
原型:numpy.swapaxes(a,axis1,axis2)
作用:交换数组的两个轴
参数 说明
a 要操作的数组
axis1 对应第一个轴的整数
axis2 对应第二个轴的整数
import numpy as np
arr = np.arange(24).reshape(2,3,4)
print("arr:\n",arr,"\n")
print("\n",arr.shape,"\n")
arr2 = np.swapaxes(arr,2,0)
print("arr:\n",arr2,"\n")
print("\n",arr2.shape,"\n")
arr:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
(2, 3, 4)
arr:
[[[ 0 12]
[ 4 16]
[ 8 20]]
[[ 1 13]
[ 5 17]
[ 9 21]]
[[ 2 14]
[ 6 18]
[10 22]]
[[ 3 15]
[ 7 19]
[11 23]]]
(4, 3, 2)
一定要支持作者哦