numpy数组中的几个元素

时间:2019-07-15 03:43:45

标签: python arrays numpy-ndarray n-dimensional

我有一个具有不同值的一维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]]

2 个答案:

答案 0 :(得分:0)

您可以使用itertools软件包中的combinations来想象这样的事情。我还使用sklearn.metrics.pairwise_distances计算所有成对距离:

from itertools import combinations
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)]

答案 1 :(得分:0)

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]]