如果我们有一维数组
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
如何获得2D数组排序的“ 2D索引”?
应用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]]])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句