我有一个数字数组,我想创建另一个数组,表示第一个数组中每个项目的排名.我正在使用Python和NumPy.
例如:
array = [4,2,7,1]
ranks = [2,1,3,0]
Run Code Online (Sandbox Code Playgroud)
这是我提出的最佳方法:
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = numpy.arange(len(array))[temp.argsort()]
Run Code Online (Sandbox Code Playgroud)
有没有更好/更快的方法避免两次排序数组?
我试图让索引按最后一个轴排序一个多维数组,例如
>>> a = np.array([[3,1,2],[8,9,2]])
Run Code Online (Sandbox Code Playgroud)
我想要这样的指数i,
>>> a[i]
array([[1, 2, 3],
[2, 8, 9]])
Run Code Online (Sandbox Code Playgroud)
根据numpy.argsort的文档,我认为它应该这样做,但我收到错误:
>>> a[np.argsort(a)]
IndexError: index 2 is out of bounds for axis 0 with size 2
Run Code Online (Sandbox Code Playgroud)
编辑:我需要以相同的方式重新排列相同形状的其他数组(例如,b这样的数组a.shape == b.shape)......这样
>>> b = np.array([[0,5,4],[3,9,1]])
>>> b[i]
array([[5,4,0],
[9,3,1]])
Run Code Online (Sandbox Code Playgroud)