本文介绍了在numpy中为二维数组选择索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这在1维上效果很好:
# This will sort bar by the order of the values in foo
(Pdb) bar = np.array([1,2,3])
(Pdb) foo = np.array([5,4,6])
(Pdb) bar[np.argsort(foo)]
array([2, 1, 3])
但是我该如何在两个维度上做到这一点? Argsort效果很好,但是选择不再起作用:
But how do I do that in two dimensions? Argsort works nicely, but the select no longer works:
(Pdb) foo = np.array([[5,4,6], [9,8,7]])
(Pdb) bar = np.array([[1,2,3], [1,2,3]])
(Pdb) bar[np.argsort(foo)]
*** IndexError: index (2) out of range (0<=index<=1) in dimension 0
(Pdb)
我希望它能输出:
array([[2, 1, 3], [3, 2, 1]])
有什么线索怎么做?
谢谢!/YGA
take()
似乎做对了,但实际上它只从第一行中提取元素(超级混乱).
take()
would seem to do the right thing, but it really only takes elements from the first row (super confusing).
您可以看到,如果我更改bar的值:
You can see that if I change the values of bar:
(Pdb) bar = np.array([["1","2","3"], ["A", "B", "C"]])
(Pdb) bar.take(np.argsort(foo))
array([['2', '1', '3'],
['3', '2', '1']],
dtype='|S1')
(Pdb)
推荐答案
bar.take(np.argsort(foo))
产生了所需的输出,因此您应该查看其文档,以确保它确实可以满足您的要求.
bar.take(np.argsort(foo))
produced your desired output, so you should take a look at its documentation to make sure it actually does what you think you want.
尝试一下:bar.take(np.argsort(foo.ravel()).reshape(foo.shape))
这篇关于在numpy中为二维数组选择索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!