用于多维ndarray的argsort [英] argsort for a multidimensional ndarray

查看:117
本文介绍了用于多维ndarray的argsort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取索引以按最后一个轴对多维数组进行排序,例如

I'm trying to get the indices to sort a multidimensional array by the last axis, e.g.

>>> a = np.array([[3,1,2],[8,9,2]])

我想要索引i这样,

>>> a[i]
array([[1, 2, 3],
       [2, 8, 9]])

基于 numpy.argsort 的文档我以为应该这样做,但是却出现了错误:

Based on the documentation of numpy.argsort I thought it should do this, but I'm getting the error:

>>> a[np.argsort(a)]
IndexError: index 2 is out of bounds for axis 0 with size 2


我需要以相同的方式重新排列其他形状相同的其他数组(例如,数组b这样的a.shape == b.shape)...以便


I need to rearrange other arrays of the same shape (e.g. an array b such that a.shape == b.shape) in the same way... so that

>>> b = np.array([[0,5,4],[3,9,1]])
>>> b[i]
array([[5,4,0],
       [9,3,1]])

推荐答案

解决方案:

>>> a[np.arange(np.shape(a)[0])[:,np.newaxis], np.argsort(a)]
array([[1, 2, 3],
       [2, 8, 9]])


您说得对,尽管我不会将其描述为欺骗索引.


You got it right, though I wouldn't describe it as cheating the indexing.

也许这将使它更清晰:

In [544]: i=np.argsort(a,axis=1)

In [545]: i
Out[545]: 
array([[1, 2, 0],
       [2, 0, 1]])

i是我们想要的每一行的顺序.那就是:

i is the order that we want, for each row. That is:

In [546]: a[0, i[0,:]]
Out[546]: array([1, 2, 3])

In [547]: a[1, i[1,:]]
Out[547]: array([2, 8, 9])

要同时执行两个索引步骤,我们必须在第一个维度上使用列"索引.

To do both indexing steps at once, we have to use a 'column' index for the 1st dimension.

In [548]: a[[[0],[1]],i]
Out[548]: 
array([[1, 2, 3],
       [2, 8, 9]])

可以与i配对的另一个数组是:

Another array that could be paired with i is:

In [560]: j=np.array([[0,0,0],[1,1,1]])

In [561]: j
Out[561]: 
array([[0, 0, 0],
       [1, 1, 1]])

In [562]: a[j,i]
Out[562]: 
array([[1, 2, 3],
       [2, 8, 9]])

如果i标识每个元素的列,则j指定每个元素的行. [[0],[1]]列数组也可以正常工作,因为它可以针对i进行广播.

If i identifies the column for each element, then j specifies the row for each element. The [[0],[1]] column array works just as well because it can be broadcasted against i.

我想到了

np.array([[0],
          [1]])

作为j的简捷".它们共同定义了新数组每个元素的源行和列.他们在一起工作,而不是顺序工作.

as 'short hand' for j. Together they define the source row and column of each element of the new array. They work together, not sequentially.

a到新数组的完整映射为:

The full mapping from a to the new array is:

[a[0,1]  a[0,2]  a[0,0]
 a[1,2]  a[1,0]  a[1,1]]


def foo(a):
    i = np.argsort(a, axis=1)
    return (np.arange(a.shape[0])[:,None], i)

In [61]: foo(a)
Out[61]: 
(array([[0],
        [1]]), array([[1, 2, 0],
        [2, 0, 1]], dtype=int32))
In [62]: a[foo(a)]
Out[62]: 
array([[1, 2, 3],
       [2, 8, 9]])

这篇关于用于多维ndarray的argsort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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