我有两个数组 my_arr
和 distances
。例如:
my_arr= np.array([0, 1, 3, 4, 5, 3, 5])
distances = np.array([18, 47, 20, 10, 26, 22, 13])
我想根据最小距离获取形状为 np.unique(my_arr).size
的索引数组。所以在前面的例子中,我会得到:
# indices of my_arr
indices_of_my_arr= np.array([0, 1, 2, 3, 6])
除了 for
循环或 map
有没有聪明的方法来做到这一点?
编辑: 另一个例子:
my_arr = np.array([0, 2, 3, 1, 3, 4, 4, 5])
dist = np.array([10, 12, 15, 18, 5, 14, 45, 8])
我希望:
[0, 1, 3, 4, 5, 7]
最佳答案
您可以使用 np.lexsort
和 np.unique
-
idx = np.lexsort([distances, my_arr])
out = np.sort(idx[np.unique(my_arr[idx], return_index=1)[1]])
关于python - 保留基于另一个数组的数组中的唯一值,同时保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087811/