2017-07-25 34 views
-2

我希望得到一個主numpy的2D陣列A的交叉行的索引,用另一個B.指數相交numpy的2D陣列的行

A = array([[1,2], 
      [1,3], 
      [2,3], 
      [2,4], 
      [2,5], 
      [3,4] 
      [4,5]]) 

B = array([[1,2], 
      [3,2], 
      [2,4]]) 

result=[0, -2, 3] 
##Note that the intercept 3,2 must assign (-) because it is the opposite 

當本應返回[0,-2 ,3]基於陣列A的指數。

謝謝!

回答

0

您可以參考代碼。

import numpy as np 
A = np.array([[1,2], 
      [1,3], 
      [2,3], 
      [2,4], 
      [2,5], 
      [3,4], 
      [4,5]]) 

B = np.array([[1,2], 
      [3,2], 
      [2,4]]) 

result=[] 

for i in range(0, len(A)): 
    for j in range(0, len(B)): 
     if A[i].tolist() == B[j].tolist(): 
      result.append(i) 
     if A[i].tolist()[::-1] == B[j].tolist(): 
      result.append(-i) 
print(result) 

的輸出是:

[0, -2, 3] 
+0

很好!但我有50個1000行的數組,這個循環變得 不可行這樣的大陣,謝謝! –

0

numpy_indexed包(聲明:我其作者)具有以下功能:有效地解決這樣的問題。

import numpy_indexed as npi 
A = np.sort(A, axis=1) 
B = np.sort(B, axis=1) 
result = npi.indices(A, B) 
result *= (A[:, 0] == B[:, 0]) * 2 - 1 
+0

謝謝!這對我的情況非常有用,但結果都是負面的,只有倒過來的結果纔會消極,我該如何解決這個問題? –

+0

應該在排序前評估== –