and

NumPy provides various sorting methods. These sorting functions implement different sorting algorithms, each characterized by execution speed, worst-case performance, required work space, and algorithm stability. The table below shows a comparison of three sorting algorithms.

Kind Speed Worst case Work space Stability
'quicksort'(quicksort) 1 O(n^2) 0 no
'mergesort'(mergesort) 2 O(n*log(n)) ~n/2 Yes
'heapsort'(heapsort) 3 O(n*log(n)) 0 no

numpy.sort()

The numpy.sort() function returns a sorted copy of the input array. The function format is as follows:

numpy.sort(a, axis, kind, order)

Parameter description:

  • a: The array to be sorted
  • axis: The axis along which to sort the array. If not provided, the array is flattened and sorted along the last axis. axis=0 sorts by column, axis=1 sorts by row.
  • kind: Default is 'quicksort'
  • order: If the array contains fields, this is the field(s) to sort by

respectively.

import numpy as np a = np.array([[3,7],[9,1]]) print ('Our array is:') print (a) print ('\n') print ('Calling the sort() function:') print (np.sort(a)) print ('\n') print ('Sort by column:') print (np.sort(a, axis = 0)) print ('\n') # Sort fields in the sort function dt = np.dtype([('name', 'S10'),('age', int)]) a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt) print ('Our array is:') print (a) print ('\n') print ('Sort by name:') print (np.sort(a, order = 'name'))

The output result is:

我们的数组是:
[[3 7]
 [9 1]]


调用 sort() 函数:
[[3 7]
 [1 9]]


按列排序:
[[3 1]
 [9 7]]


我们的数组是:
[(b'raju', 21) (b'anil', 25) (b'ravi', 17) (b'amar', 27)]


按 name 排序:
[(b'amar', 27) (b'anil', 25) (b'raju', 21) (b'ravi', 17)]

numpy.argsort()

The numpy.argsort() function returns the indices that would sort the array values from smallest to largest.

Example

import numpy as np x = np.array([3, 1, 2]) print ('Our array is:') print (x) print ('\n') print ('Calling the argsort() function on x:') y = np.argsort(x) print (y) print ('\n') print ('Reconstruct the original array in sorted order:') print (x[y]) print ('\n') print ('Reconstruct the original array using a loop:') for i in y: print (x[i], end=" ")

The output result is:

我们的数组是:
[3 1 2]


对 x 调用 argsort() 函数:
[1 2 0]


以排序后的顺序重构原数组:
[1 2 3]


使用循环重构原数组

1 2 3

numpy.lexsort()

numpy.lexsort() is used to sort multiple sequences. Think of it as sorting a spreadsheet, where each column represents a sequence, and when sorting, priority is given to the later columns.

Here is an application scenario: In the primary-to-junior high school entrance exam, students are admitted to key classes based on total score. When total scores are tied, students with higher math scores are admitted first; when both total scores and math scores are tied, admission is based on English scores... Here, total score is placed in the last column of the spreadsheet, math score in the second-to-last column, and English score in the third-to-last column.

Example

import numpy as np nm = ('raju','anil','ravi','amar') dv = ('f.y.', 's.y.', 's.y.', 'f.y.') ind = np.lexsort((dv,nm)) print ('Calling the lexsort() function:') print (ind) print ('\n') print ('Use this index to obtain the sorted data:') print ([nm[i] + ", " + dv[i] for i in ind])

The output result is:

调用 lexsort() 函数:
[3 1 0 2]


使用这个索引来获取排序后的数据:
['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']

What was passed to np.lexsort above is a tuple. When sorting, nm is sorted first, with the order: amar, anil, raju, ravi. In summary, the sort result is [3 1 0 2].

msort、sort_complex、partition、argpartition

FunctionDescription
msort(a)Sort the array along the first axis, returning a sorted copy of the array. np.msort(a) is equivalent to np.sort(a, axis=0).
sort_complex(a) Sort complex numbers in the order of real part first, then imaginary part.
partition(a, kth[, axis, kind, order]) Specify a number to partition the array
argpartition(a, kth[, axis, kind, order]) The algorithm can be specified via the keyword kind to partition the array along the specified axis

Complex sorting:

>>> import numpy as np
>>> np.sort_complex([5, 3, 6, 2, 1])
array([ 1.+0.j,  2.+0.j,  3.+0.j,  5.+0.j,  6.+0.j])
>>>
>>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
array([ 1.+2.j,  2.-1.j,  3.-3.j,  3.-2.j,  3.+5.j])

partition() partition sorting:

>>> a = np.array([3, 4, 2, 1])
>>> np.partition(a, 3)  # 将数组 a 中所有元素(包括重复元素)从小到大排列,3 表示的是排序数组索引为 3 的数字,比该数字小的排在该数字前面,比该数字大的排在该数字的后面
array([2, 1, 3, 4])
>>>
>>> np.partition(a, (1, 3)) # 小于 1 的在前面,大于 3 的在后面,1和3之间的在中间
array([1, 2, 3, 4])

Find the 3rd smallest (index=2) and 2nd largest (index=-2) values of the array

>>> arr = np.array([46, 57, 23, 39, 1, 10, 0, 120])
>>> arr[np.argpartition(arr, 2)[2]]
10
>>> arr[np.argpartition(arr, -2)[-2]]
57

Also find the 3rd and 4th smallest values. Note that here, [2,3] sorts the 3rd and 4th smallest values at once, which can then be accessed via indices

>>> arr[np.argpartition(arr, [2,3])[2]]
10
>>> arr[np.argpartition(arr, [2,3])[3]]
23

numpy.argmax() and numpy.argmin()

The numpy.argmax() and numpy.argmin() functions return the indices of the maximum and minimum elements along a given axis, respectively.

Example

import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) print ('Our array is:') print (a) print ('\n') print ('Calling the argmax() function:') print (np.argmax(a)) print ('\n') print ('Flatten the array:') print (a.flatten()) print ('\n') print ('Index of the maximum value along axis 0:') maxindex = np.argmax(a, axis = 0) print (maxindex) print ('\n') print ('Index of the maximum value along axis 1:') maxindex = np.argmax(a, axis = 1) print (maxindex) print ('\n') print ('Calling the argmin() function:') minindex = np.argmin(a) print (minindex) print ('\n') print ('Minimum value in the flattened array:') print (a.flatten()[minindex]) print ('\n') print ('Index of the minimum value along axis 0:') minindex = np.argmin(a, axis = 0) print (minindex) print ('\n') print ('Index of the minimum value along axis 1:') minindex = np.argmin(a, axis = 1) print (minindex)

The output result is:

我们的数组是:
[[30 40 70]
 [80 20 10]
 [50 90 60]]


调用 argmax() 函数:
7


展开数组:
[30 40 70 80 20 10 50 90 60]


沿轴 0 的最大值索引:
[1 2 0]


沿轴 1 的最大值索引:
[2 0 1]


调用 argmin() 函数:
5


展开数组中的最小值:
10


沿轴 0 的最小值索引:
[0 1 1]


沿轴 1 的最小值索引:
[0 2 0]

numpy.nonzero()

The numpy.nonzero() function returns the indices of non-zero elements in the input array.

Example

import numpy as np a = np.array([[30,40,0],[0,20,10],[50,0,60]]) print ('Our array is:') print (a) print ('\n') print ('Calling the nonzero() function:') print (np.nonzero (a))

The output result is:

我们的数组是:
[[30 40  0]
 [ 0 20 10]
 [50  0 60]]


调用 nonzero() 函数:
(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))

numpy.where()

The numpy.where() function returns the indices of elements in the input array that satisfy a given condition.

Example

import numpy as np x = np.arange(9.).reshape(3, 3) print ('Our array is:') print (x) print ( 'Indices of elements greater than 3:') y = np.where(x > 3) print (y) print ('Use these indices to obtain the elements that satisfy the condition:') print (x[y])

The output result is:

我们的数组是:
[[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]
大于 3 的元素的索引:
(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))
使用这些索引来获取满足条件的元素:
[4. 5. 6. 7. 8.]

numpy.extract()

The numpy.extract() function extracts elements from an array based on a condition, returning the elements that satisfy the condition.

Example

import numpy as np x = np.arange(9.).reshape(3, 3) print ('Our array is:') print (x) # Define condition, select even elements condition = np.mod(x,2) == 0 print ('Condition values by element:') print (condition) print ('Use the condition to extract elements:') print (np.extract(condition, x))

The output result is:

我们的数组是:
[[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]
按元素的条件值:
[[ True False  True]
 [False  True False]
 [ True False  True]]
使用条件提取元素:
[0. 2. 4. 6. 8.]
Other extensions