gpt4 book ai didi

python - numpy argsort 是否返回二维索引数组?

转载 作者:太空狗 更新时间:2023-10-29 17:55:26 27 4
gpt4 key购买 nike

如果我们有一个一维数组

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

我需要的是对整个矩阵进行排序的二维索引。像这样:

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

如何获取二维数组排序的“二维索引”?

最佳答案

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

关于python - numpy argsort 是否返回二维索引数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577375/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com