Home > Net >  is there a method for finding the indexes of a 2d-array based on a given array
is there a method for finding the indexes of a 2d-array based on a given array

Time:09-21

suppose we have two arrays like these two:

A=np.array([[1, 4, 3, 0, 5],[6, 0, 7, 12, 11],[20, 15, 34, 45, 56]])
B=np.array([[4, 5, 6, 7]])

I intend to write a code in which I can find the indexes of an array such as A based on values in the array B for example, I want the final results to be something like this:

C=[[0 1]
   [0 4]
   [1 0]
   [1 2]]

can anybody provide me with a solution or a hint?

CodePudding user response:

Do you mean?

In [375]: np.isin(A,B[0])
Out[375]: 
array([[False,  True, False, False,  True],
       [ True, False,  True, False, False],
       [False, False, False, False, False]])
In [376]: np.argwhere(np.isin(A,B[0]))
Out[376]: 
array([[0, 1],
       [0, 4],
       [1, 0],
       [1, 2]])

B shape of (1,4) where the initial 1 isn't necessary. That's why I used B[0], though isin, via in1d ravels it anyways.

where is result is often more useful

In [381]: np.where(np.isin(A,B))
Out[381]: (array([0, 0, 1, 1]), array([1, 4, 0, 2]))

though it's a bit harder to understand.

Another way to get the isin array:

In [383]: (A==B[0,:,None,None]).any(axis=0)
Out[383]: 
array([[False,  True, False, False,  True],
       [ True, False,  True, False, False],
       [False, False, False, False, False]])

CodePudding user response:

You can try in this way by using np.where().

index = []
for num in B:
    for nums in num:
        x,y = np.where(A == nums)
        index.append([x,y])
    
print(index)

>>array([[0,1],
        [0,4],
        [1,0],
        [1,2]])

CodePudding user response:

With zip and np.where:

>>> list(zip(*np.where(np.in1d(A, B).reshape(A.shape))))
[(0, 1), (0, 4), (1, 0), (1, 2)]

Alternatively:

>>> np.vstack(np.where(np.isin(A,B))).transpose()
array([[0, 1],
       [0, 4],
       [1, 0],
       [1, 2]], dtype=int64)
  • Related