numpy中的反向数组索引

6ljaweal  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(104)

我在numpy中有一个数组和索引列表:

ar = np.array([4, 5, 3, -1, -1, 0, 1, 2])
indices = np.array([5, 6, 1, 2, 0, 7, 3, 4])

ar_permuted = ar[indices]
#ar_permuted = array([0, 1, 5, 3, 4, 2, -1, -1])

字符串
现在,给定ar_permuted和索引,恢复ar的最直接方法是什么?

fcg9iug3

fcg9iug31#

假设所有索引都存在。
使用argsort

out = ar_permuted[np.argsort(indices)]

字符串
使用索引:

out = np.zeros(shape=len(ar_permuted), dtype=ar_permuted.dtype)
out[indices] = ar_permuted


输出量:

array([ 4,  5,  3, -1, -1,  0,  1,  2])

相关问题