0

If I have a large array and a small array, for example

A = np.array([1,2,3])
B = np.array([3,4,5,6,7,8,2,1])

I can use np.intersect1d to get the same value, but if I want to get the index (in large array B)of same value, for this example,it should be [0,6,7],is there any command to get it?

1 Answer 1

1

You can use np.in1d() to get a Boolean array that represents the places where items of A appears in B, then using np.where() or np.argwhere() function you can get the indices of the True items:

In [8]: np.where(np.in1d(B, A))[0]
Out[8]: array([0, 6, 7])

Or as mentioned in comments np.in1d(B, A).nonzero()[0]. However the way you wanna choose here depends pretty much on the reset of your program and where/how you wanna use the results. In addition you can run benchmarks on all the methods in both short and large arrays to see which one is more appropriate in which situation.

Sign up to request clarification or add additional context in comments.

2 Comments

Or maybe np.in1d(B, A).nonzero()[0]
@coldspeed Sure, added to the answer.

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.