lhk*_*lhk 5 python arrays numpy
我想对 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]
Run Code Online (Sandbox Code Playgroud)
一个简单的解决方案使用numpy.searchsorted
np.searchsorted(np.sort(a), a)
# produces [0, 3, 1, 2]
Run Code Online (Sandbox Code Playgroud)
我对这个解决方案不满意,因为它看起来效率很低。它分两个单独的步骤进行排序和搜索。
对于具有重复项的数组,这种奇特的索引会失败,请查看:
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))
Run Code Online (Sandbox Code Playgroud)
您只需要反转对数组进行排序的排列即可。如链接问题所示,您可以这样做:
import numpy as np
def sorted_position(array):
a = np.argsort(array)
a[a.copy()] = np.arange(len(a))
return a
print(sorted_position([0.1, 0.2, 0.0, 0.5, 0.8, 0.4, 0.7, 0.3, 0.9, 0.6]))
# [1 2 0 5 8 4 7 3 9 6]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2793 次 |
| 最近记录: |