有numpy argsort返回一个2d索引数组?

pep*_*dip 11 python arrays numpy

如果我们有一个1d数组

arr = np.random.randint(7, size=(5))
# [3 1 4 6 2]
print np.argsort(arr)
# [1 4 0 2 3] <= The indices in the sorted order    
Run Code Online (Sandbox Code Playgroud)

如果我们有一个2d数组

arr = np.random.randint(7, size=(3, 3))
# [[5 2 4]
# [3 3 3]
# [6 1 2]]
print np.argsort(arr)
# [[1 2 0]
# [0 1 2]
# [1 2 0]] <= It sorts each row
Run Code Online (Sandbox Code Playgroud)

我需要的是2d索引,它将整个矩阵排序.像这样的东西:

# [[2 1] => 1
# [0 1] => 2
# [2 2] => 2
# .
# .
# .
# [0 2] => 4
# [0 0] => 5
# [2 0]] => 6
Run Code Online (Sandbox Code Playgroud)

如何获得2d数组排序的"2d索引"?

Ash*_*ary 26

应用于展numpy.argsort平的阵列,然后将指数解开回(3,3)形状:

>>> arr = np.array([[5, 2, 4],
[3, 3, 3],
[6, 1, 2]])
>>> np.dstack(np.unravel_index(np.argsort(arr.ravel()), (3, 3)))
array([[[2, 1],
        [0, 1],
        [2, 2],
        [1, 0],
        [1, 1],
        [1, 2],
        [0, 2],
        [0, 0],
        [2, 0]]])
Run Code Online (Sandbox Code Playgroud)

  • jezz,这是什么结果......? (3认同)
  • 我认为你最后需要一个“[0]”? (2认同)

Moz*_*zak 6

从关于numpy.argsort的文档:

ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
Run Code Online (Sandbox Code Playgroud)

N 维数组的排序元素的索引。

一个例子:

>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
       [2, 2]])
>>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
>>> ind # a tuple of arrays containing the indexes
(array([0, 1, 1, 0]), array([0, 0, 1, 1]))
>>> x[ind]  # same as np.sort(x, axis=None)
array([0, 2, 2, 3])
Run Code Online (Sandbox Code Playgroud)