gpt4 book ai didi

python - numpy 数组中的几个元素

转载 作者:行者123 更新时间:2023-12-01 07:34:50 24 4
gpt4 key购买 nike

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

最佳答案

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

关于python - numpy 数组中的几个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57033017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com