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

时间:2022-12-03 21:40:47

If we have a 1d array

如果我们有一个一维数组

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    

If we have a 2d array

如果我们有一个二维数组

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

What I need is the 2d indices that sort this matrix in it's entirety. Something like this:

我需要的是二维的指标来对这个矩阵进行整体排序。是这样的:

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

How do I get "2d indices" for the sorting of a 2d array?

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

1 个解决方案

#1


22  

Apply numpy.argsort on flattened array and then unravel the indices back to (3, 3) shape:

应用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


22  

Apply numpy.argsort on flattened array and then unravel the indices back to (3, 3) shape:

应用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]]])