numpy.argsort() in python, returns the index of the array according to the size

A = array([ 0,  0,  0,  0,  2,  0,  0,  0,  2,  0,  0,  0,  0,  0,  0,  0,  0,
       13,  0,  0,  3,  0,  0,  0,  0,  0,  0,  2,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  4,  0,  1,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  4,  0,  0,  0,  0,  0, 11,  0,  3,
        0,  0,  2, 11,  0,  0,  0,  1,  0,  0,  0,  1,  2,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 11,  0])
# 按照数值大小降序排列,返回对应的index
A.argsort()[::-1]

return:

array([17, 65, 98, 71, 43, 59, 20, 67, 80, 70, 4, 27, 8, 45, 75, 79, 30,
31, 29, 28, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 26, 99, 25,
24, 1, 2, 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19,
21, 22, 44, 23, 49, 46, 47, 77, 78, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 76, 74, 73, 57, 48, 50, 51, 52,
53, 54, 55, 56, 58, 72, 60, 61, 62, 63, 64, 66, 68, 69, 0])

# 按照数值大小升序排列,返回对应的index
A.argsort()

return:

array([ 0, 69, 68, 66, 64, 63, 62, 61, 60, 72, 58, 56, 55, 54, 53, 52,
51, 50, 48, 57, 73, 74, 76, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87,
86, 85, 84, 83, 82, 81, 78, 77, 47, 46, 49, 23, 44, 22, 21, 19, 18,
16, 15, 14, 13, 12, 11, 10, 9, 7, 6, 5, 3, 2, 1, 24, 25, 99,
26, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 28, 29, 31, 30, 79,
75, 45, 8, 27, 4,70, 80, 67, 20, 59, 43, 71, 98, 65, 17])

Other methods: (This method seems simple, but there will be exceptions during the actual test, and the results are not necessarily returned to the index in strict order)

# 按照数值大小升序排列,返回对应的index
np.argsort(A)

# 按照数值大小降序排列,返回对应的index
np.argsort(-A)

Guess you like

Origin blog.csdn.net/weixin_45281949/article/details/106235014