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

时间:2015-06-01 15:28:19

标签: python arrays numpy

如果我们有一个数组

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    

如果我们有一个二维数组

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

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

# [[2 1] => 1
# [0 1] => 2
# [2 2] => 2
# .
# .
# .
# [0 2] => 4
# [0 0] => 5
# [2 0]] => 6

我如何获得&#34; 2d指数&#34;用于分类二维数组?

2 个答案:

答案 0 :(得分:24)

在展平的数组上应用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]]])

答案 1 :(得分:2)

摘自numpy.argsort上的文档:

ind = np.unravel_index(np.argsort(x, axis=None), x.shape)

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])enter code here