[SciPy-user] Returning the positions of a sorted array
Steve Schmerler
elcorto at gmx.net
Wed Sep 19 07:33:34 EDT 2007
Perez Kawumi wrote:
> Hullo,
> Im having problems returning the positions of a sorted array.
>
> Say I create an array
> a = ([3,5,1])
>
> then if I use the sort command I get
>
> sort(a) = [1,3,5]
>
> But what if i want the actual original positions of the sorted array to be returned instead. Is there a command in python that can do this?
>
> I'm looking for an answer of the form [2,0,1] which returns the original positions in a of the sorted array instead.
>
In [7]: numpy.*sort*?
numpy.argsort
numpy.lexsort
numpy.msort
numpy.searchsorted
numpy.sort
numpy.sort_complex
In [8]: numpy.argsort?
Type: function
Base Class: <type 'function'>
String Form: <function argsort at 0xa762b6f4>
Namespace: Interactive
File: /usr/lib/python2.4/site-packages/numpy/core/fromnumeric.py
Definition: numpy.argsort(a, axis=-1, kind='quicksort', order=None)
Docstring:
Returns array of indices that index 'a' in sorted order.
Keyword arguments:
axis -- axis to be indirectly sorted (default -1)
Can be None to indicate return indices into the
flattened array.
kind -- sorting algorithm (default 'quicksort')
Possible values: 'quicksort', 'mergesort', or 'heapsort'
order -- For an array with fields defined, this argument allows
specification of which fields to compare first, second,
etc. Not all fields need be specified.
Returns: array of indices that sort 'a' along the specified axis.
This method executes an indirect sort along the given axis using the
algorithm specified by the kind keyword. It returns an array of indices of
the same shape as 'a' that index data along the given axis in sorted order.
The various sorts are characterized by average speed, worst case
performance, need for work space, and whether they are stable. A stable
sort keeps items with the same key in the same relative order. The three
available algorithms have the following properties:
|------------------------------------------------------|
| kind | speed | worst case | work space | stable|
|------------------------------------------------------|
|'quicksort'| 1 | O(n^2) | 0 | no |
|'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes |
|'heapsort' | 3 | O(n*log(n)) | 0 | no |
|------------------------------------------------------|
All the sort algorithms make temporary copies of the data when the sort is not
along the last axis. Consequently, sorts along the last axis are faster
and use
less space than sorts along other axis.
In [10]: a = numpy.array([3,5,1])
In [11]: numpy.argsort(a)
Out[11]: array([2, 0, 1])
In [12]: a.*sort*?
a.argsort
a.searchsorted
a.sort
In [13]: a.argsort()
Out[13]: array([2, 0, 1])
--
cheers,
steve
Random number generation is the art of producing pure gibberish as quickly as
possible.
More information about the SciPy-User
mailing list