我想根据另一个带索引的 numpy 向量对一个 numpy 向量进行排序。
import numpy as np
my_vector = np.array([9. 6. 21. 17. 12.])
my_indices = np.array([1. 4. 2. 0. 3.])
what_i_want = np.array([17. 9. 21. 12. 6.])
有这个功能吗?类似反向 argsort 的东西
请您参考如下方法:
可以使用高级赋值在 O(n) 中完成:
my_vector = np.array([9., 6., 21., 17., 12.])
my_indices = np.array([1., 4., 2., 0., 3.])
my_result = np.empty_like(my_vector)
my_result[my_indices.astype(int)] = my_vector
my_result
# array([17., 9., 21., 12., 6.])
更大例子的时间:
from timeit import timeit
a = np.random.random(1000000)
b = np.random.permutation(1000000).astype(float)
def fargsort():
return(a[b.argsort()])
def fassign():
c = np.empty_like(a)
c[b.astype(int)] = a
return c
np.all(fargsort() == fassign())
# True
timeit(fargsort,number=10)
# 1.2764090860000579
timeit(fassign,number=10)
# 0.17262099700747058
