NumPyの基本:配列の転置
元の行列のi行j列の要素が、j行i列の要素になった行列
【書式】
np.transpose(配列, 形状)
配列.transpose()
配列.T
【コード】
import numpy as np
# 乱数の固定
np.random.seed(0)
# 元配列作成
arr1=np.random.randint(1,10,(2,3,4))
print(arr1)
print(arr1.shape)
print("\n\n")
# テスト
print("転置後")
print("np.transpose(配列)\n※形状オプション無\n",np.transpose(arr1),"\n")
print("np.transpose(配列, 形状)\n",np.transpose(arr1,(2,1,0)),"\n")
print("配列.transpose()\n※形状オプション無\n",arr1.transpose(),"\n")
print("配列.transpose(形状)\n",arr1.transpose*1,"\n")
print("配列.T\n",arr1.T)
【結果】
[[[6 1 4 4]
[8 4 6 3]
[5 8 7 9]]
[[9 2 7 8]
[8 9 2 6]
[9 5 4 1]]]
(2, 3, 4)
転置後
np.transpose(配列)
※形状オプション無
[[[6 9]
[8 8]
[5 9]]
[[1 2]
[4 9]
[8 5]]
[[4 7]
[6 2]
[7 4]]
[[4 8]
[3 6]
[9 1]]]
np.transpose(配列, 形状)
[[[6 9]
[8 8]
[5 9]]
[[1 2]
[4 9]
[8 5]]
[[4 7]
[6 2]
[7 4]]
[[4 8]
[3 6]
[9 1]]]
配列.transpose()
※形状オプション無
[[[6 9]
[8 8]
[5 9]]
[[1 2]
[4 9]
[8 5]]
[[4 7]
[6 2]
[7 4]]
[[4 8]
[3 6]
[9 1]]]
配列.transpose(形状)
[[[6 9]
[8 8]
[5 9]]
[[1 2]
[4 9]
[8 5]]
[[4 7]
[6 2]
[7 4]]
[[4 8]
[3 6]
[9 1]]]
配列.T
[[[6 9]
[8 8]
[5 9]]
[[1 2]
[4 9]
[8 5]]
[[4 7]
[6 2]
[7 4]]
[[4 8]
[3 6]
[9 1]]]
全て同じ動作になる。
【書式】
np.transpose(配列, 形状)
配列.transpose(形状)
引数が少々複雑。図参照。
【コード】
import numpy as np
# 乱数の固定
np.random.seed(0)
# 元配列作成
arr1=np.random.randint(1,10,(2,3,4))
print("arr1=\n",arr1)
print("arr1.shape=\n",arr1.shape)
print("\n\n")
print("arr1(変換後1)=\n",np.transpose(arr1,(1,0,2)))
print("\n\n")
print("arr1(変換後2)=\n",arr1.transpose((1,0,2)))
【結果】
arr1=
[[[6 1 4 4]
[8 4 6 3]
[5 8 7 9]]
[[9 2 7 8]
[8 9 2 6]
[9 5 4 1]]]
arr1.shape=
(2, 3, 4)
arr1(変換後1)=
[[[6 1 4 4]
[9 2 7 8]]
[[8 4 6 3]
[8 9 2 6]]
[[5 8 7 9]
[9 5 4 1]]]
arr1(変換後2)=
[[[6 1 4 4]
[9 2 7 8]]
[[8 4 6 3]
[8 9 2 6]]
[[5 8 7 9]
[9 5 4 1]]]
*1:2,1,0