簡體   English   中英

python找到兩個numpy數組的交點

[英]python find the intersection point of two numpy array

我有兩個描述空間曲線的numpy數組,它們在一個點上相交,我想在兩個數組中找到該交點的最近值,我有這個代碼可以正常運行,但是對於大量的點來說它的速度很慢。

from scipy import spatial
def nearest(arr0, arr1):
    ptos = []
    j = 0
    for i in arr0:
        distance, index = spatial.KDTree(arr1).query(i)
        ptos.append([distance, index, j])
        j += 1
    ptos.sort()
    return (arr1[ptos[0][1]].tolist(), ptos[0][1], ptos[0][2])

結果將是(<point coordinates>,<position in arr1>,<position in arr0>)

你的代碼正在做很多你不需要的事情。 首先,你在每個循環中重建KDtree,這是一種浪費。 query需要一個點數組,因此無需編寫自己的循環。 Ptos是一種奇怪的數據結構,你不需要它(並且不需要對它進行排序)。 嘗試這樣的事情。

from scipy import spatial

def nearest(arr0, arr1):
    tree = spatial.KDTree(arr1)
    distance, arr1_index = tree.query(arr0)
    best_arr0 = distance.argmin()
    best_arr1 = arr1_index[best_arr0]
    two_closest_points = (arr0[best_arr0], arr1[best_arr1])
    return two_closest_points, best_arr1, best_arr0

如果仍然不夠快,您需要更詳細地描述您的問題,並找出其他搜索算法是否能更好地解決您的問題。

暫無
暫無

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

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