[Numpy-discussion] how to use argsort result?

Pau Gargallo pau.gargallo at gmail.com
Tue Jul 11 05:37:23 CDT 2006


On 7/11/06, Stefan van der Walt <stefan at sun.ac.za> wrote:
> On Tue, Jul 11, 2006 at 11:32:48AM +0200, Emanuele Olivetti wrote:
> > Hi,
> > I don't understand how to use argsort results. I have a 2D matrix and
> > I want to sort values in each row and obtain the index array of that
> > sorting. Argsort(1) is what I need, but the problem is how to use its
> > result in order to obtain a sorted matrix. Here is the simple example:
> >
> > A = array([[2,3,1],[5,4,6]])
> > indexes = a.argsort(1)
> >
> > now indexes is:
> > array([[2, 0, 1],
> >         [1, 0, 2]])
> >
> > I'd like to apply indexes to A and obtain:
> > array([[1, 2, 3],
> >         [4, 5, 6]])
> >
> > or better, I'm interested both in a subset of indexes, i.e. indexes[:,1:], and
> > the related values of A matrix.
> >
> > How can I do this? If I simpy say: A[indexes] I get an IndexError.
>
> Something's not quite right here.  The argsort docstring states that:
>
>     argsort(a,axis=-1) return the indices into a of the sorted array
>     along the given axis, so that take(a,result,axis) is the sorted array.
>
> But
>
> N.take(A,A.argsort()) breaks.  Either this is a bug, or the docstring
> needs to be updated.
>
> Cheers
> Stéfan
>

I think the docstring is wrong, because take doesn't do that.
if you N.take(A,A.argsort(1), 1), it doesn't break but it doesn't sort
A neither.

Take seems to peek entire columns, but take's docstring is missing.

For the argsort docstring, it may be usefull to indicate that if one do
>>> ind = indices(A.shape)
>>> ind[ax] = A.argsort(axis=ax)
then A[ind] is the sorted array.


pau




More information about the Numpy-discussion mailing list