NumPy-インデックス作成とスライス
ndarrayオブジェクトのコンテンツは、Pythonの組み込みコンテナオブジェクトと同じように、インデックス作成またはスライスによってアクセスおよび変更できます。
前述のように、ndarrayオブジェクトのアイテムはゼロベースのインデックスに従います。3種類のインデックス作成方法が利用可能です-field access, basic slicing そして advanced indexing。
基本的なスライスは、Pythonの基本的な概念であるn次元へのスライスの拡張です。Pythonスライスオブジェクトは、start, stop、および step ビルトインへのパラメータ slice関数。このスライスオブジェクトは、配列の一部を抽出するために配列に渡されます。
例1
import numpy as np 
a = np.arange(10) 
s = slice(2,7,2) 
print a[s]その出力は次のとおりです-
[2  4  6]上記の例では、 ndarray オブジェクトはによって準備されます arange()関数。次に、スライスオブジェクトは、開始値、停止値、およびステップ値2、7、および2でそれぞれ定義されます。このスライスオブジェクトがndarrayに渡されると、インデックス2から7までのステップ2のオブジェクトの一部がスライスされます。
同じ結果は、コロンで区切られたスライスパラメータ:( start:stop:step)を直接に与えることによっても取得できます。 ndarray オブジェクト。
例2
import numpy as np 
a = np.arange(10) 
b = a[2:7:2] 
print bここでは、同じ出力が得られます-
[2  4  6]パラメータを1つだけ入力すると、インデックスに対応する1つのアイテムが返されます。その前に:を挿入すると、そのインデックス以降のすべてのアイテムが抽出されます。2つのパラメーター(それらの間に:を含む)が使用される場合、デフォルトのステップ1で2つのインデックス(停止インデックスを含まない)の間の項目がスライスされます。
例3
# slice single item 
import numpy as np 
a = np.arange(10) 
b = a[5] 
print bその出力は次のとおりです-
5例4
# slice items starting from index 
import numpy as np 
a = np.arange(10) 
print a[2:]これで、出力は次のようになります。
[2  3  4  5  6  7  8  9]例5
# slice items between indexes 
import numpy as np 
a = np.arange(10) 
print a[2:5]ここで、出力は次のようになります。
[2  3  4]上記の説明は多次元に適用されます ndarray あまりにも。
例6
import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 
print a  
# slice items starting from index
print 'Now we will slice the array from the index a[1:]' 
print a[1:]出力は次のとおりです-
[[1 2 3]
 [3 4 5]
 [4 5 6]]
Now we will slice the array from the index a[1:]
[[3 4 5]
 [4 5 6]]スライスには省略記号(…)を含めて、配列の次元と同じ長さの選択タプルを作成することもできます。行の位置で省略記号を使用すると、行の項目で構成されるndarrayが返されます。
例7
# array to begin with 
import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 
print 'Our array is:' 
print a 
print '\n'  
# this returns array of items in the second column 
print 'The items in the second column are:'  
print a[...,1] 
print '\n'  
# Now we will slice all items from the second row 
print 'The items in the second row are:' 
print a[1,...] 
print '\n'  
# Now we will slice all items from column 1 onwards 
print 'The items column 1 onwards are:' 
print a[...,1:]このプログラムの出力は次のとおりです-
Our array is:
[[1 2 3]
 [3 4 5]
 [4 5 6]] 
 
The items in the second column are: 
[2 4 5] 
The items in the second row are:
[3 4 5]
The items column 1 onwards are:
[[2 3]
 [4 5]
 [5 6]]