[Numpy-discussion] is there a sortrows

josef.pktd at gmail.com josef.pktd at gmail.com
Sun Dec 21 23:37:20 EST 2008


On Sun, Dec 21, 2008 at 11:10 PM, Pierre GM <pgmdevlist at gmail.com> wrote:
>
> On Dec 21, 2008, at 10:19 PM, josef.pktd at gmail.com wrote:
>>
>>> From the examples that I tried out np.sort, sorts each column
>> separately (with axis = 0). If the elements of a row is supposed to
>> stay together, then np.sort doesn't work
>
> Well, if the elements are supposed to stay together, why wouldn't you
> tie them first, sort, and then untie them ?
>
>  >>> np.sort(a.view([('',int),('',int)]),0).view(int)
>
> The first view transforms your 2D array into a 1D array of tuples, the
> second one retransforms the 1D array to 2D.
>
> Not sure it's better than your lexsort, haven't timed it.

That's very helpful, not so much about the sort but it's a good
example to move back and forth between structured and regular arrays.
My help search for this was not successful enough to figure this out
by myself. Several functions require structured arrays but I didn't
know how to get them without specifying everything by hand. And when I
have a structured array, I didn't know how to call var or mean on
them.

Your suggestion also works with automatic adjustment for number of columns.

>>> np.sort(a.view([('','<i4')]*a.shape[1]),0).view(int)

Thanks,

Josef



More information about the NumPy-Discussion mailing list