[Numpy-discussion] argsort
Robert Kern
robert.kern@gmail....
Wed Jan 16 02:39:10 CST 2013
On Wed, Jan 16, 2013 at 9:30 AM, Mads Ipsen <madsipsen@gmail.com> wrote:
> Hi,
>
> Thanks everybody for all the answers that make perfect sense when axis=0.
>
> Now suppose I want to sort the array in such a way that each row is sorted
> individually. Then I suppose I should do this:
>
> from numpy import *
>
>
> v = array([[4,3],
> [1,12],
> [23,7],
> [11,6],
> [8,9]])
> idx = argsort(v, axis=1)
>
> idx is then
>
> [[1 0]
> [0 1]
> [1 0]
> [1 0]
> [0 1]]
>
> which makes sense, since these are the indices in an order that would sort
> each row. But when I try
>
> a[idx, variuos_additional_arguments]
>
> I just get strange results. Anybody that can point me towards the correct
> solution.
Please have a look at the documentation again. If idx has indices for
the second axis, you need to put it into the second place.
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing-multi-dimensional-arrays
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
[~]
|4> idx0 = np.arange(v.shape[0])[:,np.newaxis]
[~]
|5> idx0
array([[0],
[1],
[2],
[3],
[4]])
[~]
|7> v[idx0, idx]
array([[ 3, 4],
[ 1, 12],
[ 7, 23],
[ 6, 11],
[ 8, 9]])
--
Robert Kern
More information about the NumPy-Discussion
mailing list