【发布时间】:2019-06-24 20:28:53
【问题描述】:
我想对一个 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))
【问题讨论】: