[Numpy-discussion] is there a sortrows

josef.pktd@gmai... josef.pktd@gmai...
Sun Dec 21 22:52:13 CST 2008


On Sun, Dec 21, 2008 at 11:37 PM,  <josef.pktd@gmail.com> wrote:
> On Sun, Dec 21, 2008 at 11:10 PM, Pierre GM <pgmdevlist@gmail.com> wrote:
>>
>> On Dec 21, 2008, at 10:19 PM, josef.pktd@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
>

Version with fully automatic conversion, I don't even have to know the dtype

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

(this is for future Google searches)

Josef


More information about the Numpy-discussion mailing list