Abstract
Performs a sort along the given axis using the algorithm specified. It returns an array of indices of the same shape.
Function
Method
Property
Signature
- Function
argsort (arr, axis=-1, kind='quick', order=None)
- Method
arr.argsort (axis=-1, kind='quick', order=None)
Arguments
- return
an array of indices of the same shape as arr.
- arr
- Array to be sorted.
- axis
- The axis the sort is applied to in a multi-dimensional array.
- kind
The underlying algorithm to use. see: Sorting Algorithms for details.
- 'quick'
- 'heap'
- 'merge'
- order
- Used for arrays with fields defined. Can be one of the following:
- A single string.
- Indicates that field as the basis for the sort.
- A list or tuple of strings.
- Basis is in list order.
- None
- If fields are defined, then the first field is the basis.
- A single string.
Details
Sorting Algorithms
- 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
Examples
1 >>> from numpy import *
2 >>> a = array([2,0,8,4,1])
3 >>> ind = a.argsort() # indices of sorted array using quicksort (default)
4 >>> ind
5 array([1, 4, 0, 3, 2])
6 >>> a[ind] # same effect as a.sort()
7 array([0, 1, 2, 4, 8])
8 >>> ind = a.argsort(kind='merge') # algorithm options are 'quicksort', 'mergesort' and 'heapsort'
9 >>> a = array([[8,4,1],[2,0,9]])
10 >>> ind = a.argsort(axis=0) # sorts on columns. NOT the same as a.sort(axis=1)
11 >>> ind
12 array([[1, 1, 0],
13 [0, 0, 1]])
14 >>> a[ind,[[0,1,2],[0,1,2]]] # 2-D arrays need fancy indexing if you want to sort them.
15 array([[2, 0, 1],
16 [8, 4, 9]])
17 >>> ind = a.argsort(axis=1) # sort along rows. Can use a.argsort(axis=-1) for last axis.
18 >>> ind
19 array([[2, 1, 0],
20 [1, 0, 2]])
21 >>> a = ones(17)
22 >>> a.argsort() # quicksort doesn't preserve original order.
23 array([ 0, 14, 13, 12, 11, 10, 9, 15, 8, 6, 5, 4, 3, 2, 1, 7, 16])
24 >>> a.argsort(kind="mergesort") # mergesort preserves order when possible. It is a stable sort.
25 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
26 >>> ind = argsort(a) # there is a functional form
Notes
xxx
See Also
lexsort : Indirect stable sort on multiple keys.
sort : Find keys in sorted array.