0

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?

3
  • Use C[row,col] to access elements. Commented Sep 19, 2021 at 16:20
  • @SwapnalShahil I think the OP is looking for how to generate C, not index it. Commented Sep 19, 2021 at 16:33
  • Yeah sorry about that and thanks for clearing! Commented Sep 19, 2021 at 16:39

3 Answers 3

1

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]])
Sign up to request clarification or add additional context in comments.

Comments

0

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]])

Comments

0

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)

1 Comment

That list(zip(* is a list based transpose. np.argwhere is np.transpose(np.where(...)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.