Python | numpy输出排名
引言
我们知道np.sort()
可以对向量进行排序,而排名怎么做呢,mark下。
先简单介绍下np.sort()
和np.argsort()
这两个函数
排序 np.sort()
排序,默认升序
import numpy as np
temp = np.array([0,1,2,3,4,5,4])
tsort = np.sort(temp)
tsort
array([0, 1, 2, 3, 4, 4, 5])
排序序号 np.argsort()
返回排序对应序号,默认升序序号,照样放代码:
import numpy as np
temp = np.array([0,1,2,3,4,5,4])
tindex = np.argsort(temp)
tindex
array([0, 1, 2, 3, 4, 6, 5], dtype=int32)
如果是想得到降序序号:
import numpy as np
temp = np.array([0,1,2,3,4,5,4])
tindex = np.argsort(-temp)
tindex
array([5, 4, 6, 3, 2, 1, 0], dtype=int32)
排名
其实用两次np.argsort()
就好了~
import numpy as np
temp = np.array([0,1,2,3,4,5,4])
tindex = np.argsort(-temp)
trank = np.argsort(tindex)
trank
array([6, 5, 4, 3, 1, 0, 2], dtype=int32)
一句话简写: np.argsort(np.argsort(-temp))