簡體   English   中英

查找與 numpy 數組中元素的最小絕對差相對應的值

[英]Find values corresponding to the minimum absolute difference of elements in a numpy array

我有一個形狀為 (n, m) 的 arrays 數組,以及一個形狀為 (m) 的數組 b。 我想創建一個數組 c 包含來自 a 的元素,這些元素最接近 b 的相應元素。 我可以用這段代碼做到這一點:

a = [[11, 2, 9, 4, 5], [4, 4, 6, 1, -2]]
b = [1, 3, 12, 0, 0]
c = []

for inner in range(len(a[0])):
    min_distance = float('inf')
    best_index = 0
    for outer in range(len(a)):
        current_distance = abs(b[inner] - a[outer][inner])
        if min_distance > current_distance:
            min_distance = current_distance
            best_index = outer
    c.append(a[best_index][inner])

print(c)
# [4, 2, 9, 1, -2]

當 a (ei a[0][1] 和 a[1][1]) 中的兩個元素距離相等,但在 b (ei b[1] ])。 如何使用 numpy 做到這一點?

a = np.array(a)
b = np.array(b)
a[abs(a-b).argmin(0), np.arange(a.shape[1])]

暫無
暫無

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

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