首页 > 解决方案 > 如何在python的for循环中自动查找numpy数组中的匹配项

问题描述

我想在其他两个数组中搜索数组的索引,并想找出它们匹配的位置。首先,我有一个变量,它表示将匹配多少点它被称为brk。这brk等于我的搜索数组 ( searched) 的长度。在我的简单情况下brk = 2,这意味着我将有 4 个匹配点 ( brk * 2)。所以,我必须将我的搜索brk数组分成两半,然后在每个主数组(main_x_arrmain_y_arr)中搜索每一半。我总是有一个搜索数组和两个主数组,但是brk会更改并说 ho 来搜索索引。目前我正在手动创建每个匹配项,但我正在尝试自动创建匹配项。这是我的代码:

searched=np.array([[1., 2.], [-3., 1.]])
brk=len(searched)
main_y_arr=np.array([[1., 5.], [8., 3.], [-3., 8.], [2., 4.]])
main_x_arr=np.array([[1., 7.], [-3., 1.], [4., 7.], [2., 4.]])
match1= np.min (np.unique (np.where((main_y_arr==searched[:int (len(searched)/2)].reshape (-1,1)[:,None]).any(-1))[1]))
match2= np.max (np.unique (np.where((main_x_arr==searched[:int (len(searched)/2):].reshape (-1,1)[:,None]).any(-1))[1]))
match3= np.min (np.unique (np.where((main_y_arr==searched[int (len(searched)/2):].reshape (-1,1)[:,None]).any(-1))[1]))
match4= np.max (np.unique (np.where((main_x_arr==searched[int (len(searched)/2):].reshape (-1,1)[:,None]).any(-1))[1]))

可以看出,我正在创建每场比赛,但我想找到一种方法来首先知道我会有2 * brk比赛。然后,将searched数组拆分为数量,然后搜索每个匹配brk的数组中的每个拆分。如果我的数组4的长度等于,那么我将有 thre splits 和 finall (eactly like repeating and for three slices to make 6 match)。或者如果是,我将只有匹配项(就像只有一张幻灯片一样),因为它不能再被拆分。在此之前,我非常感谢任何帮助和反馈。searched36match1match212match1match2

标签: pythonarraysnumpyfor-loop

解决方案


经过长时间的讨论,我们决定这解决了 OP 的要求:

matches = []
for current_search in searched:
    current_search_reshaped = current_search.reshape(-1,1,1)
    match_min = np.min(np.unique(np.where((main_y_arr == current_search_reshaped).any(-1))[1]))
    match_max = np.max(np.unique(np.where((main_x_arr == current_search_reshaped).any(-1))[1]))
    matches.append((match_min, match_max))

推荐阅读