NumPy:【shapeの数値】を別々に取り出す
サマリ
- 要素数
- shapeの表示結果にある数値
- 個別に取り出すにはshape[0]、shape[1]、…
- 次元数
- shapeの表示結果にある数値の個数
- np.ndimでも取得可能
はじめに
前提
- np.arange
- np.reshape
- np.ndim
ndarrayにまつわる数字
- shapeの実行結果が(4, 3)なら
- 1次元目の要素数が4、2次元目の要素数が3
- 次元数は()内の数字の個数で2
- 参考
- 次元の数え方(1次元目、2次元目、…)については下記記事の「次元の呼び方」を参照
サンプルコード
1次元の場合
import numpy as np
a = np.array([3,4])
print(a)
print(a.shape)
print('ndim:'+str(a.ndim))
print(a.shape[0])
[3 4] (2,) ndim:1 2
- (2, )なので1次元のndarray(NumPy配列)
- ndimも「1」になっている
- shape[0]で1次元目の要素数「2」を取り出せる
- shape[1]は存在しないのでエラーになる
- 「IndexError: tuple index out of range」
2次元の場合
import numpy as np
a = np.arange(12).reshape(4,3)
print(a)
print(a.shape)
print('ndim:'+str(a.ndim))
print(a.shape[0])
print(a.shape[1])
[[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] (4, 3) ndim:2 4 3
- (4, 3)なので2次元のndarray(NumPy配列)
- ndimも2になっている
- shape[0]で1次元目の要素数「4」を取り出せる
- shape[1]で2次元目の要素数「3」を取り出せる
- shape[2]は存在しないのでエラーになる
- 「IndexError: tuple index out of range」
3次元の場合
import numpy as np
a = np.arange(24).reshape(2,3,4)
print(a)
print(a.shape)
print('ndim:'+str(a.ndim))
print(a.shape[0])
print(a.shape[1])
print(a.shape[2])
[[[ 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) ndim:3 2 3 4
- (2,3,4)なので3次元のndarray(NumPy配列)
- ndimも3になっている
- shape[0]で1次元目の要素数「2」を取り出せる
- shape[1]で2次元目の要素数「3」を取り出せる
- shape[2]で3次元目の要素数「4」を取り出せる
- shape[3]は存在しないのでエラーになる
- 「IndexError: tuple index out of range」

