查找 python 中其他数组中出现的数组的所有索引

finding all the indices of an array occuring in other arrays in python

我有一个 numpy 数组,想在另外两个数组中搜索搜索数组所在的索引:

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

我想在 main_arr1 中搜索 searched 数组的前半部分,在 main_arr2 中搜索后半部分(实际上 searched 数组要长得多,但我会把它分成两部分:上半场和下半场):

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

得到:

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

但我的代码只给我:

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

我不知道为什么它会忽略其他索引。如果有人帮助我解决这个问题,我将不胜感激。

我找到了解决问题的方法,但我认为还有更聪明的解决方案。我只是通过重塑我的形状数组来做到这一点:

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]

在重塑之前,它每行有两个数字,但我将其重塑为每个数字是一行 (reshape (-1,1))。 尽管如此,我还是很欣赏更快、更集成的解决方案。

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