numpy argsort 是否返回一个二维索引数组? [英] Have numpy argsort return an array of 2d indices?
本文介绍了numpy argsort 是否返回一个二维索引数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们有一个一维数组
arr = np.random.randint(7, size=(5))# [3 1 4 6 2]打印 np.argsort(arr)# [1 4 0 2 3] <= 排序后的索引
如果我们有一个二维数组
arr = np.random.randint(7, size=(3, 3))# [[5 2 4]# [3 3 3]# [6 1 2]]打印 np.argsort(arr)# [[1 2 0]# [0 1 2]# [1 2 0]] <= 对每一行进行排序
我需要的是对整个矩阵进行排序的二维索引.像这样:
# [[2 1] =>1# [0 1] =>2# [2 2] =>2# .# .# .# [0 2] =>4# [0 0] =>5# [2 0]] =>6
我如何获得二维索引"?用于对二维数组进行排序?
解决方案
在扁平数组上应用 numpy.argsort
,然后将索引解开回 (3, 3) 形状:
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 its 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?
解决方案
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屋!
查看全文