<分区>
我想对一个 numpy 数组进行排序,并找出每个元素的去向。
numpy.argsort
会告诉我排序数组中的每个索引,未排序数组中的哪个索引去那里。我正在寻找类似逆向的东西:对于未排序数组中的每个索引,它在排序数组中的位置。
a = np.array([1, 4, 2, 3])
# a sorted is [1,2,3,4]
# the 1 goes to index 0
# the 4 goes to index 3
# the 2 goes to index 1
# the 3 goes to index 2
# desired output
[0, 3, 1, 2]
# for comparison, argsort output
[0, 2, 3, 1]
一个简单的解决方案是使用 numpy.searchsorted
np.searchsorted(np.sort(a), a)
# produces [0, 3, 1, 2]
我对这个解决方案不满意,因为它看起来效率很低。它分两个独立的步骤进行排序和搜索。
对于有重复的数组,这种奇特的索引失败了,看:
a = np.array([1, 4, 2, 3, 5])
print(np.argsort(a)[np.argsort(a)])
print(np.searchsorted(np.sort(a),a))
a = np.array([1, 4, 2, 3, 5, 2])
print(np.argsort(a)[np.argsort(a)])
print(np.searchsorted(np.sort(a),a))