python - 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]]
解决方案
您可以想象这样的事情,使用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)]
推荐阅读
- c++ - 是否可以稍后修改传递给 listen() 调用的积压值而不关闭 Windows 上 Winsock2 C++ 中的侦听套接字?
- r - Subset the first three years of each group of a data.table
- ios - iOS 14 小部件不刷新
- c# - C#以相反的顺序打印一个字符串数组
- c++ - 如何在 sfml 中检查与矩形形状的碰撞
- php - PHPmailer 意外 HTTP ERROR 500,语法似乎没问题
- mysql - 这是正确的 PDO 并且足以防止注射吗?
- javascript - Javascript - 为什么 forEach 方法添加了重复项?
- javascript - 跨多个 React 组件共享一个 JavaScript 类
- javascript - 根据单选按钮选择,只需要一些 HTML 字段