首页 > 解决方案 > finding all the indices of an array occuring in other arrays in python

问题描述

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.

标签: pythonarraysnumpywhere-clause

解决方案


一种解决方案可能是使用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]

输出:

>>> match1
array([0, 3])
>>> match2
array([0, 1])

推荐阅读