2012-07-14 12 views
27

2つのnumpy配列間の交差点のインデックスを取得するにはどうすればよいですか?Python:交差インデックスnumpy配列

import numpy as np 

a = np.array(xrange(11)) 
b = np.array([2, 7, 10]) 
inter = np.intersect1d(a, b) 
# inter == array([ 2, 7, 10]) 

をしかし、どのように、私はinterの値のaにインデックスを取得することができます:私はintersect1dと交差する値を得ることができますか?

答えて

31

in1dによって生成されたブール値配列を使用して、arangeのインデックスを付けることができます。

>>> a[::-1] 
array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) 
>>> a = a[::-1] 

intersect1dはまだ同じ値...

>>> numpy.intersect1d(a, b) 
array([ 2, 7, 10]) 

を返しますが、ブール配列in1d返します:

>>> numpy.in1d(a, b) 
array([ True, False, False, True, False, False, False, False, True, 
     False, False], dtype=bool) 

インデックスが値と異なっているようにaを逆転範囲をインデックスするために使用できます:

>>> numpy.arange(a.shape[0])[numpy.in1d(a, b)] 
array([0, 3, 8]) 
>>> indices = numpy.arange(a.shape[0])[numpy.in1d(a, b)] 
>>> a[indices] 
array([10, 7, 2]) 

しかし、あなたはnonzeroを使用することができ、上記を簡単にするために - それはXYの一様なリストのタプルを返すので、これは、おそらく最も正しいアプローチです...座標:

>>> numpy.nonzero(numpy.in1d(a, b)) 
(array([0, 3, 8]),) 

か、等価:

>>> numpy.in1d(a, b).nonzero() 
(array([0, 3, 8]),) 

結果が問題なくaと同じ形状の配列へのインデックスとして使用することができます。

>>> a[numpy.nonzero(numpy.in1d(a, b))] 
array([10, 7, 2]) 

しかし、多くの状況下で、それだけでなく非ブール指標のセットに変換するよりも、ブール配列自体を使用することが理にかなっていることに注意してください。

最後に、ブール値配列をargwhereに渡すこともできます。これは、インデックス作成には適していないが、他の目的には便利なやや異なる形の結果を生成します。

>>> numpy.argwhere(numpy.in1d(a, b)) 
array([[0], 
     [3], 
     [8]]) 
+2

だから荒いが、それは動作します:) 簡単にオクターブで: [間indexA indexB] =が交差(A、B) – invis

+0

がためにあなたをたくさんありがとうあなたの答え ! – invis

+0

in1dとintersect1dは同じではありません。 intersect1dは一意の値を与え、in1dはすべての交点を与え、この答えは常に働かない。 – Rik

2

あなたはintersect1dによって与えられるように一意の値を取得する必要がある場合:

import numpy as np 

a = np.array([range(11,21), range(11,21)]).reshape(20) 
b = np.array([12, 17, 20]) 
print(np.intersect1d(a,b)) 
#unique values 

inter = np.in1d(a, b) 
print(a[inter]) 
#you can see these values are not unique 

indices=np.array(range(len(a)))[inter] 
#These are the non-unique indices 

_,unique=np.unique(a[inter], return_index=True) 

uniqueIndices=indices[unique] 
#this grabs the unique indices 

print(uniqueIndices) 
print(a[uniqueIndices]) 
#now they are unique as you would get from np.intersect1d() 

出力:

[12 17 20] 
[12 17 20 12 17 20] 
[1 6 9] 
[12 17 20] 
0

は、我々はステップでこのステップを通過してみましょう。

その他のソリューション

まず、特性を使用して、ゼロ

c = np.zeros(len(a)) 
print c 
>>> [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] 

第二に、インデックス

c[inter] = 1 
print c 
>>>[ 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 1.] 

交差する最後のステップを使用して、Cの変更の配列値でnumpyの配列を作成しますnp.nonzero()の場合、インデックスが0以外の用語

inter_with_idx = np.nonzero(c) 
print inter_with_idx 
>>>array([ 2, 7, 10]) 

リファレンス

[1] numpy.nonzero