1

I have a numpy array and want to search for the indices where the search array exists in two other arrays:

searched=np.array([[1., 2.], [-3., 1.]])

I want to search for first half of searched array in main_arr1 and second half in main_arr2 (in reality searched array is much more longer but I will split it into two ones: first half and second half):

main_arr1=np.array([[1., 5.], [8., 3.], [-3., 8.], [2., 4.]])
main_arr2=np.array([[1., 7.], [-3., 1.], [4., 7.], [2., 4.]])

Then, I tried:

match1=np.where((main_arr1==searched[:int (len(searched)/2)][:,None]).any(-1))[1]
match2=np.where((main_arr2==searched[int (len(searched)/2):][:,None]).any(-1))[1]

to get:

match1=np.array([0., 3.])
match2=np.array([0., 1.])

But my code is only giving me:

match1=np.array([0.])
match1=np.array([1.])

I do not know why it is ignoring other indices. I do appreciate if anyone help me to solve this problem.

2 Answers 2

1

One solution could be using np.isin

searched=np.array([[1., 2.], [-3., 1.]])

main_arr1=np.array([[1., 5.], [8., 3.], [-3., 8.], [2., 4.]])
main_arr2=np.array([[1., 7.], [-3., 1.], [4., 7.], [2., 4.]])

match1 = np.where(np.isin(main_arr1,searched[:len(searched)//2]).any(-1))[0]
match2 = np.where(np.isin(main_arr2,searched[len(searched)//2:]).any(-1))[0]

Output:

>>> match1
array([0, 3])
>>> match2
array([0, 1])
Sign up to request clarification or add additional context in comments.

Comments

0

I found a way to solve my problem but I think there are more clever solutions. I did it just by reshaping my shape array:

match1=np.where((main_arr1==searched[:int (len(searched)/2)].reshape (-1,1)[:,None]).any(-1))[1]
match2=np.where((main_arr2==searched[int (len(searched)/2):].reshape (-1,1)[:,None]).any(-1))[1]

Before reshape it has two numbers in each row but I made it to be reshaped as each number be a row (reshape (-1,1)). Still, I do appreciate faster and more integrated solutions.

Comments

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.