ndim | 配列の次元を取得します。 |
shape | 配列の(行列)型を取得します。 |
size | 配列要素の数を取得します。 |
dtype | 配列のデータ型を取得します。 |
>>> x = np.random.normal(0,10,(3,5)) #配列の次元取得 >>> x.ndim 2 #配列の型を取得 >>> x.shape (3, 5) #配列の要素数を取得 >>> x.size 15 #配列のデータ型を取得 >>> x.dtype dtype('float64')
#5×5行列を作成 >>> A=np.array([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,18],[20,21,22,23,24]]) >>> A array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 18], [20, 21, 22, 23, 24]])
#Aの2行目を取得 >>> A[1] array([5, 6, 7, 8, 9])
#Aの2、4行目を取得 >>> A[[1,3]] array([[ 5, 6, 7, 8, 9], [15, 16, 17, 18, 19]])
#Aの2~4行目を取得 >>> A[1:4] array([[ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]])
#Aの5列目を取得 >>> A[:,4] array([ 4, 9, 14, 19, 24])
#Aの3、4列目を取得 >>> A[:, [2,3]] array([[ 2, 3], [ 7, 8], [12, 13], [17, 18], [22, 23]])
#Aの3~5列目を取得 >>> A[:, 2:5] array([[ 2, 3, 4], [ 7, 8, 9], [12, 13, 14], [17, 18, 19], [22, 23, 24]])
#Aの2行3列目(2, 3)を取得 >>> A[1,2] 7 >>> A[1][2] 7
#Aの2行2列目、3行3列目、4行4列目の要素を取得 >>> A[[1,2,3],[1,2,3]] array([ 6, 12, 18]) #行と列の指定数が一致しない場合はエラー >>> A[[1,2,3],[2,3]] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)
#Aの2~4行目と3~5列目の共通部を取得 >>> A[1:4, 2:5] array([[ 7, 8, 9], [12, 13, 14], [17, 18, 19]])
#Aの2~3行目をBに入力 >>> B = A[1:3] >>> B array([[ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> type(B) #Bの型はnumpy配列 <class 'numpy.ndarray'> >>> C = np.array(A[1:3,2:5]) >>> C array([[ 7, 8, 9], [12, 13, 14]])
>>> A[1,0] 5 >>> A[1,0]=500 >>> A array([[ 0, 1, 2, 3, 4], [500, 6, 7, 8, 9], [ 10, 11, 12, 13, 14], [ 15, 16, 17, 18, 18], [ 20, 21, 22, 23, 24]]) >>> B array([[500, 6, 7, 8, 9], [ 10, 11, 12, 13, 14]])
#Aを元に戻して >>> A[1,0]=5 >>> A array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 18], [20, 21, 22, 23, 24]]) #copyメソッドを使う場合 >>> B = A[1:3].copy() >>> B array([[ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> A[1,0]=500 >>> A array([[ 0, 1, 2, 3, 4], [500, 6, 7, 8, 9], [ 10, 11, 12, 13, 14], [ 15, 16, 17, 18, 18], [ 20, 21, 22, 23, 24]]) >>> B array([[ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) #Bの要素は変わっていません。