python - 保留基于另一个数组的数组中的唯一值,同时保留顺序

标签 python numpy

我有两个数组 my_arrdistances。例如:

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.lexsortnp.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/

相关文章:

python - 检查字典数组中的键值对并相应更新另一个列表

python - 在 python 中,如何从我的 distutils 包中公开一些命令?

python - 类型错误: 'numpy.ndarray' 对象在使用 pandas .values() 时不可调用

python - B 在 A 中的值(value)位置索引

python - numpy:对操作结果执行 "any"或 "all"的有效方法

python - 在 Python 中编译 C DLL 并与之交互可以在 Unix 上运行,但不能在 Windows 上运行。这样做的正确方法是什么?

python - 从 Python 编写 Excel 2003 XML

python - 通过在 OPENCV 和实时视频中使用固有矩阵和畸变系数来进行相机校准

python - 从 C 代码序列化数组数据,在 Python 中反序列化

python - 将非唯一、未排序的数组与唯一、已排序的数组中的索引进行匹配