# [Numpy-discussion] 1D array sorting ascending and descending by fields

Chris Barker chris.barker at noaa.gov
Mon Jun 4 18:08:35 EDT 2012

```On Mon, Jun 4, 2012 at 11:10 AM, Patrick Redmond <plredmond at gmail.com> wrote:
> Here's how I sorted primarily by field 'a' descending and secondarily by
> field 'b' ascending:

could you multiply the numeric field by -1, sort, then put it back --
somethign like:

data *- -1
data_sorted = np.sort(data, order=['a','b'])
data_sorted *= -1

(reverse if necessary -- I lost track...)

-Chris

> (Note that 'a' is the second column, 'b' is the first)
>
>>>> data
> array([('b', 0.03),
>        ('c', 0.03),
>        ('f', 0.03),
>        ('e', 0.01),
>        ('d', 0.04),
>        ('a', 0.04)],
>       dtype=[('b', '|S32'), ('a', '<f8')])
>>>> data.sort(order='b') # sort by b
>>>> data = data[::-1] # reverse
>>>> data[numpy.argsort(data['a'])][::-1] # sort by a and reverse
> array([('a', 0.04),
>        ('d', 0.04),
>        ('b', 0.03),
>        ('c', 0.03),
>        ('f', 0.03),
>        ('e', 0.01)],
>       dtype=[('b', '|S32'), ('a', '<f8')])
>
> My question is whether there's an easier way to do this.

could you multipily the nubmeric field by -1, sort, then multiply it again?

Originally I
> thought it would be possible to just do:
>
>>>> data.sort(order=('-a', 'b'))
>
> ...indicating that the order of 'a' is descending, but this isn't part of
> NumPy's sort behavior.
>
>
> Thank you,
> Patrick
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>

--

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov

```