已经numpy的argsort返回二维索引数组? [英] Have numpy argsort return an array of 2d indices?

查看:1211
本文介绍了已经numpy的argsort返回二维索引数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一维数组

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

我需要的是2D指数,在它的整体排序这个矩阵。事情是这样的:

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

我如何得到2D指数为二维数组的排序?

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

推荐答案

应用 numpy.argsort 扁平阵列上,然后解开指数回(3,3)形状

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

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

这篇关于已经numpy的argsort返回二维索引数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆