-2

I want to get the indices of the intersecting rows of a main numpy 2d array A, with another one B.

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

Where this should return [0, -2, 3] based on the indices of array A.

Thank you!

2 Answers2

1

The numpy_indexed package (disclaimer: I am its author) has functionality to solve such problems efficiently.

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
Eelco Hoogendoorn
  • 10,459
  • 1
  • 44
  • 42
0

You can reference the code.

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)

The output is :

[0, -2, 3]
youDaily
  • 1,372
  • 13
  • 21