簡體   English   中英

如何在 python 的 for 循環中自動在 numpy arrays 中查找匹配項

[英]How to find matches in numpy arrays automatically in a for loop in python

我想在另外兩個 arrays 中搜索數組的索引,並想找出它們匹配的位置。 首先,我有一個變量,它表示將匹配多少點它稱為brk 這個brk等於我的搜索數組( searched )的長度。 在我的簡單情況下, brk = 2這意味着我將有 4 個匹配點( brk * 2 )。 因此,我必須將我的搜索數組分成brk兩半,然后在每個主數組( main_x_arrmain_y_arr )中搜索每一半。 我總是有一個搜索數組和兩個主要的 arrays,但是brk改變並說搜索索引。 目前我正在手動創建每個匹配項,但我正在嘗試自動創建匹配項。 這是我的代碼:

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匹配。 如果我searched的數組的長度等於3 ,那么我將有 thre splits 和 finall 6 (就像重復match1match2三個切片以進行 6 個匹配)。 或者如果它是1 ,我將只有2匹配項(就像只有一張幻燈片有match1match2一樣),因為它不能再被拆分了。 在此之前,我非常感謝任何幫助和反饋。

經過長時間的討論,我們決定這解決了 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM