首页 > 解决方案 > numpy数组中的几个元素

问题描述

我有具有不同值的一维 numpy 数组(arr0)。我想创建一个新的元素数组,其中每个元素是一个元素与其最接近的元素的一对(索引和/或值),考虑到这对的差异(距离)的绝对值低于一组临界点。

在每一步(耦合)我想删除已经耦合的元素。

arr0 = [40, 55, 190, 80, 175, 187] #My original 1D array
threshold = 20 #Returns elements if "abs(el_1 - el_2)<threshold"
#For each couple found, the code should remove the couple from the array and then go on with the next couple
result_indexes = [[0, 1], [2, 5]]
result_value = [[40, 55], [190, 187]]

标签: pythonarraysnumpy-ndarrayn-dimensional

解决方案


您可以想象这样的事情,使用sklearn.metrics.pairwise_distances来计算所有成对距离:

from sklearn.metrics import pairwise_distances

# Get all pairwise distances
distances = pairwise_distances(np.array(arr0).reshape(-1,1),metric='l1')
# Sort the neighbors by distance for each element 
neighbors_matrix = np.argsort(distances,axis=1)

result_indexes = []
result_values = []

used_indexes = set()

for i, neighbors in enumerate(neighbors_matrix):

    # Skip already used indexes
    if i in used_indexes:
        continue

    # Remaining neighbors
    remaining = [ n for n in neighbors if n not in used_indexes and n != i]
    # The closest non used neighbor is in remaining[0] is not empty
    if len(remaining) == 0:
        continue

    if distances[i,remaining[0]] < threshold:
        result_indexes.append((i,remaining[0]))
        result_values.append((arr0[i],arr0[remaining[0]]))

        used_indexes = used_indexes.union({i,remaining[0]})

在您的示例中,它产生:

>> result_indexes
[(0, 1), (2, 4)]
>> result_values
[(40, 55), (190, 175)]

推荐阅读