Numpy-indexing-and-slicing

提供:Dev Guides
移動先:案内検索

NumPy-インデックス作成とスライス

ndarrayオブジェクトの内容は、Pythonの組み込みコンテナーオブジェクトと同様に、インデックス付けまたはスライスによってアクセスおよび変更できます。

前述したように、ndarrayオブジェクトのアイテムはゼロベースのインデックスに従います。 3種類のインデックス方法が利用可能です-フィールドアクセス、基本スライシング*および*高度なインデックス

基本的なスライシングは、Pythonのn次元へのスライシングの基本概念の拡張です。 Pythonスライスオブジェクトは、組み込みの slice 関数に start、stop 、および step パラメーターを与えることで構築されます。 このスライスオブジェクトは、配列の一部を抽出するために配列に渡されます。

例1

import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]

その出力は次のとおりです-

[2  4  6]

上記の例では、 ndrange オブジェクトは* 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つだけの場合、インデックスに対応する単一のアイテムが返されます。 :がその前に挿入されると、そのインデックス以降のすべてのアイテムが抽出されます。 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([[print a

# slice items starting from index
print 'Now we will slice the array from the index a[1:]'
print a[1:]

出力は次のとおりです-

[[Now we will slice the array from the index a[1:]
[[Slicing can also include ellipsis (…) to make a selection tuple of the same length as the dimension of an array. If ellipsis is used at the row position, it will return an ndarray comprising of items in rows.

=== Example 7

[source,prettyprint,notranslate]

#import numpy as np a = np.array([[print 'Our array is:' print a print '\ n’で始まる配列

#これは、2列目の項目の配列を返しますprint '2列目の項目は次のとおりです:' print a […​、1] print '\ n'

#次に、2行目のすべてのアイテムをスライスしますprint '2行目のアイテムは:' print a [1、…​] print '\ n'

#ここで、列1以降のすべてのアイテムをスライスしますprint 'アイテム1列目以降は:' print a […​、1:]

The output of this program is as follows −

[source,result,notranslate]

配列は次のとおりです。[[2列目の項目は次のとおりです。

2行目の項目は次のとおりです。

アイテム列1以降は次のとおりです。[[