NumPy:【形状、次元、要素数】の確認方法
サマリ
- np.shape
- 形状取得
- shape[…]
- n番目の次元の要素数
- 2次元(行列)なら
- shape[0]…行数
- shape[1]…列数
- ndim
- 次元数
- shapeの結果が(2,3,1)なら3次元
前提
- np.random.randn
サンプルコード
shape(形状)
import numpy as np
a = np.array([1,2])
b = np.array([[1,2], [3,4], [5,6]])
print(a.shape)
print(b.shape)
(2,) (3, 2)
- 1つ目
- 1次元のNumPy配列
- 2つ目
- 2次元のNumPy配列
- 行列
- (3,2)の形状
shape[…](要素数取り出し)
正常パターン
import numpy as np
a = np.array([[1,2], [3,4], [5,6]])
print(a.shape)
print(a.shape[0])
print(a.shape[1])
(3, 2) 3 2
- a.shape
- (3,2)になる
- a.shape[0]
- (3,2)の3
- a.shape[1]
- (3,2)の2
次元数を超えるとエラー
import numpy as np
a = np.array([[1,2], [3,4], [5,6]])
print(a.shape) #(3, 2)
print(a.shape[2]) #エラーを想定
(3, 2)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-34-1d170bfe0be9> in <module>
2 print(a.shape) #(3, 2)
3 a = np.array([[1,2], [3,4], [5,6]])
----> 4 print(a.shape[2]) #エラーを想定
IndexError: tuple index out of range
- 次元数は
- (3,2)なので2次元
- a.shape[…]に指定するインデックス番号は0から始まる
- 2次元なので0(1番目)、1(2番目)の2つ
- a.shape[2]
- 2は3番目の次元を指しているが、存在しないのでエラー
ndim(次元)
import numpy as np
a = np.random.randn(2,2,1,2)
print(a.shape)
print(a.ndim)
(2, 2, 1, 2) 4
- a.shape
- 形状は(2,2,1,2)
- a.ndim
- 次元数が取得できるコマンド
- 2,2,1,2の4つが次元数
