Numpy-advanced-indexing

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

NumPy-高度なインデックス作成

非タプルシーケンスであるndarray、整数またはブールデータ型のndarrayオブジェクト、または少なくとも1つの項目がシーケンスオブジェクトであるタプルから選択を行うことができます。 高度なインデックスは、常にデータのコピーを返します。 これに対して、スライスはビューのみを表示します。

高度なインデックスには、*整数*と*ブール*の2種類があります。

整数のインデックス付け

このメカニズムは、N次元インデックスに基づいて配列内の任意のアイテムを選択するのに役立ちます。 各整数配列は、そのディメンションへのインデックスの数を表します。 インデックスがターゲットndarrayの次元と同じ数の整数配列で構成される場合、それは簡単になります。

次の例では、ndarrayオブジェクトの各行から指定された列の1つの要素が選択されます。 したがって、行インデックスにはすべての行番号が含まれ、列インデックスは選択される要素を指定します。

例1

import numpy as np

x = np.array([[y = x[[0,1,2], [0,1,0]]
print y

その出力は次のようになります-

[1  4  5]

選択範囲には、最初の配列の(0,0)、(1,1)、および(2,0)の要素が含まれます。

次の例では、4X3配列の角に配置された要素が選択されています。 選択の行インデックスは[0、0]および[3,3]ですが、列インデックスは[0,2]および[0,2]です。

例2

import numpy as np
x = np.array([[print 'Our array is:'
print x
print '\n'

rows = np.array([[cols = np.array([[0,2],[0,2]])
y = x[rows,cols]

print 'The corner elements of this array are:'
print y

このプログラムの出力は次のとおりです-

Our array is:
[[The corner elements of this array are:
[[The resultant selection is an ndarray object containing corner elements.

Advanced and basic indexing can be combined by using one slice (:) or ellipsis (…) with an index array. The following example uses slice for row and advanced index for column. The result is the same when slice is used for both. But advanced index results in copy and may have different memory layout.

==== Example 3

[source,prettyprint,notranslate]

numpyをnp x = np.array([[print 'Our array is:' print x print '\ n’としてインポート

#z = x [1:4,1:3]のスライス

print 'スライス後、配列は次のようになります:' print z print '\ n'

#列y = x [1:4、[1,2]]に高度なインデックスを使用

print '列に高度なインデックスを使用したスライス:' print y

The output of this program would be as follows −

[source,result,notranslate]

配列は次のとおりです。[[スライス後、配列は次のようになります。[[列の高度なインデックスを使用したスライス:[[Boolean Array Indexing

このタイプの高度なインデックスは、結果のオブジェクトが比較演算子などのブール演算の結果である場合に使用されます。

例1

この例では、ブールインデックスの結果として5を超えるアイテムが返されます。

import numpy as np
x = np.array([[print 'Our array is:'
print x
print '\n'

# Now we will print the items greater than 5
print 'The items greater than 5 are:'
print x[x > 5]

このプログラムの出力は次のようになります-

Our array is:
[[The items greater than 5 are:
[ 6  7  8  9 10 11]

例2

この例では、NaN(Not a Number)要素は〜(補数演算子)を使用して省略されています。

import numpy as np
a = np.array([np.nan, 1,2,np.nan,3,4,5])
print a[~np.isnan(a)]

その出力は-

[ 1.   2.   3.   4.   5.]

実施例3

次の例は、配列から非複雑な要素を除外する方法を示しています。

import numpy as np
a = np.array([1, 2+6j, 5, 3.5+5j])
print a[np.iscomplex(a)]

ここでは、出力は次のとおりです-

[2.0+6.j  3.5+5.j]