[SciPy-User] sorting an array
Martin
mdekauwe at gmail.com
Sat Aug 1 19:31:26 EDT 2009
Hi all,
Thanks for the replies...perhaps if I explained the context it might
help (or it might not!). Basically it is an image processing problem
so the array is rows, columns. So I want to sort the array such that
row col
1 1
1 2
1 3
etc
2 1
2 2
2 3
then I can use the other columns to create images safe in the
knowledge they are in the correct row, column 2D space. I think
Emmanuelle solution does the trick from what I can see, I am just
trying it out. Although I have never seen [:,:2] what does the :2 bit
mean?
Neil your solution results in column 4 changing some of the ordering
from what I can see (the zero in the fourth column).
Thanks a lot for the suggestions
Martin
On Aug 1, 11:26 pm, Neil Crighton <neilcrigh... at gmail.com> wrote:
> Martin <mdekauwe <at> gmail.com> writes:
>
> > When really what i wanted was not for the 3rd and 4th columns to also
> > be sorted nunmerically in that way. In unix I would reformat the first
> > two columns in gawk i.e. gawk '{printf("%2.3d %2.3d, %d, %d\n", $1,
> > $2, $3, $4)}' | sort -n -k 1
>
> I think lexsort does what you need. Get the sorted row indices:
>
> >>> a
>
> array([[ 1, 0, 2, 5],
> [ 1, 5, 6, 2],
> [ 1, 2, 8, 7],
> [ 1, 4, 4, 6],
> [ 1, 3, 2, 3],
> [ 1, 11, 2, 0],
> [ 1, 10, 1, 3],
> [ 1, 9, 0, 4],
> [ 1, 8, 9, 6]])
>
> >>> ind = np.lexsort(a.T[::-1])
>
> a.T gives an array of columns, and reversing them with ::-1 sorts by the
> first column values, then the second column values if the first column
> values are equal, and so on. Now index the the original array:
>
> >>> ind
>
> array([0, 2, 4, 3, 1, 8, 7, 6, 5])>>> a[ind]
>
> array([[ 1, 0, 2, 5],
> [ 1, 2, 8, 7],
> [ 1, 3, 2, 3],
> [ 1, 4, 4, 6],
> [ 1, 5, 6, 2],
> [ 1, 8, 9, 6],
> [ 1, 9, 0, 4],
> [ 1, 10, 1, 3],
> [ 1, 11, 2, 0]])
>
> Neil
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-U... at scipy.orghttp://mail.scipy.org/mailman/listinfo/scipy-user
More information about the SciPy-User
mailing list