在numpy数组中耦合元素

2024-04-20 07:50:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个一维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]]

Tags: thenumpy元素距离thresholdmy阈值数组
2条回答

您可以想象这样的情况,使用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]})

在您的例子中,它会产生:

^{pr2}$
arr0s = sorted(arr0)
n = len(arr0)
z = []
x = 0 
while x<n-2:
    if arr0s[x+1]-arr0s[x] < 20:
        if arr0s[x+1]-arr0s[x] < arr0s[x+2]-arr0s[x+1]:
            z.append([arr0s[x], arr0s[x+1]])
            x+=2 
        else:
            z.append([arr0s[x+1], arr0s[x+2]])
            x+=3
    else:
        x+=1 
    result_indexes = [[arr0.index(i[0]), arr0.index(i[1])]  for i in z] 

    for i, j in enumerate(result_indexes):
        if j[0]>j[1]:
            result_indexes[i] = [j[1], j[0]]
    result_value = [[arr0[i[0]], arr0[i[1]]] for i in result_indexes]
print(result_indexes)
#[[0, 1], [2, 5]]
print(result_value)
#[[40, 55], [190, 187]]

相关问题 更多 >