NumPy Sorting and Conditional Filtering Functions
NumPy provides multiple sorting methods. These sorting functions implement different sorting algorithms, each characterized by execution speed, worst-case performance, required workspace, and algorithm stability. The following table shows a comparison of three sorting algorithms.
| Kind | Speed | Worst Case | Workspace | Stability |
|---|---|---|---|---|
'quicksort'(quicksort) |
1 | O(n^2) |
0 | No |
'mergesort'(mergesort) |
2 | O(n*log(n)) |
~n/2 | Is |
'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 sort
- axis: The axis along which to sort the array; if not given, the array is flattened and sorted along the last axis; axis=0 sorts by column, axis=1 sorts by row
- kind: defaults to 'quicksort'
- order: If the array contains fields, the field to sort by
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
3
,
7
]
,
[
9
,
1
]
]
)
(
'
Our array is:
'
)
(
a
)
(
'
\n
'
)
(
'
Call the sort() function:
'
)
(
np
.
sort
(
a
)
)
(
'
\n
'
)
(
'
Sort by column:
'
)
(
np
.
sort
(
a
,
axis
=
0
)
)
(
'
\n
'
)
Sorting 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
)
(
'
Our array is:
'
)
(
a
)
(
'
\n
'
)
(
'
Sort by name:
'
)
(
np
.
sort
(
a
,
order
=
'
name
'
)
)
The output is:
我们的数组是:
[[3 7]
[9 1]]
Calling the sort() function:
[[3 7]
[1 9]]
Sort by column:
[[3 1]
[9 7]]
Our array is:
[(b'raju', 21) (b'anil', 25) (b'ravi', 17) (b'amar', 27)]
# Sort by 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
]
)
(
'
Our array is:
'
)
(
x
)
(
'
\n
'
)
(
'
Call the argsort() function on x:
'
)
y
=
np
.
argsort
(
x
)
(
y
)
(
'
\n
'
)
(
'
Reconstruct the original array in sorted order:
'
)
(
x
[
y
]
)
(
'
\n
'
)
(
'
Reconstruct the original array using a loop:
'
)
for
i
in
y
:
(
x
[
i
]
,
end
=
"
"
)
The output is:
我们的数组是:
[3 1 2]
# Call argsort() function on x:
[1 2 0]
Reconstruct the original array in sorted order:
[1 2 3]
使用循环重构原数组
1 2 3
numpy.lexsort()
numpy.lexsort() is used to sort by multiple sequences. Think of it as sorting a spreadsheet, where each column represents a sequence and sorting gives priority to later columns.
Here is an application scenario: a primary-to-junior-high school entrance exam, where students are admitted to key classes based on total scores. When total scores are equal, those with higher math scores are admitted first; when both total and math scores are equal, admission is based on English scores... Here, the total score is in the last column of the spreadsheet, math scores in the second-to-last column, and English scores 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
)
)
(
'
Call the lexsort() function:
'
)
(
ind
)
(
'
\n
'
)
(
'
Use these indices to get the sorted data:
'
)
(
[
nm
[
i
]
"
,
"
dv
[
i
]
for
i
in
ind
]
)
The output is:
调用 lexsort() 函数:
[3 1 0 2]
Use this index to get the sorted data:
['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']
What is passed to np.lexsort above is a tuple; when sorting, nm is sorted first, in the order: amar, anil, raju, ravi. The resulting sort order is [3 1 0 2].
msort、sort_complex、partition、argpartition
| function | Description |
|---|---|
| msort(a) | Sort the array along the first axis and return a sorted copy. np.msort(a) is equivalent to np.sort(a, axis=0). |
| sort_complex(a) | Sort complex numbers by 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 keyword kind can specify the algorithm to partition the array along the given axis |
Complex number 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 sort:
>>> 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) value and the 2nd largest (index=-2) value in 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
Find the 3rd and 4th smallest values at the same time. Note here that using [2,3] sorts the 3rd and 4th smallest together, then they can be retrieved via indices [2] and [3] respectively.
>>> 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
]
]
)
(
'
Our array is:
'
)
(
a
)
(
'
\n
'
)
(
'
Call the argmax() function:
'
)
(
np
.
argmax
(
a
)
)
(
'
\n
'
)
(
'
Flatten the array:
'
)
(
a
.
flatten
(
)
)
(
'
\n
'
)
(
'
Index of the maximum value along axis 0:
'
)
maxindex
=
np
.
argmax
(
a
,
axis
=
0
)
(
maxindex
)
(
'
\n
'
)
(
'
Index of the maximum value along axis 1:
'
)
maxindex
=
np
.
argmax
(
a
,
axis
=
1
)
(
maxindex
)
(
'
\n
'
)
(
'
Call the argmin() function:
'
)
minindex
=
np
.
argmin
(
a
)
(
minindex
)
(
'
\n
'
)
(
'
Minimum value in the flattened array:
'
)
(
a
.
flatten
(
)
[
minindex
]
)
(
'
\n
'
)
(
'
Index of the minimum value along axis 0:
'
)
minindex
=
np
.
argmin
(
a
,
axis
=
0
)
(
minindex
)
(
'
\n
'
)
(
'
Index of the minimum value along axis 1:
'
)
minindex
=
np
.
argmin
(
a
,
axis
=
1
)
(
minindex
)
The output is:
我们的数组是:
[[30 40 70]
[80 20 10]
[50 90 60]]
Call the argmax() function:
7
Expand array:
[30 40 70 80 20 10 50 90 60]
Index of the maximum value along axis 0:
[1 2 0]
Index of the maximum value along axis 1:
[2 0 1]
Call the argmin() function:
5
Expand the minimum value in the array:
10
Index of the minimum value along axis 0:
[0 1 1]
Index of the minimum value along axis 1:
[0 2 0]
numpy.nonzero()
The numpy.nonzero() function returns the indices of the non-zero elements in the input array.
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
30
,
40
,
0
]
,
[
0
,
20
,
10
]
,
[
50
,
0
,
60
]
]
)
(
'
Our array is:
'
)
(
a
)
(
'
\n
'
)
(
'
Call the nonzero() function:
'
)
(
np
.
nonzero
(
a
)
)
The output is:
我们的数组是:
[[30 40 0]
[ 0 20 10]
[50 0 60]]
Call the nonzero() function:
(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
(
)
.
reshape
(
3
,
3
)
(
'
Our array is:
'
)
(
x
)
(
'
Indices of elements greater than 3:
'
)
y
=
np
.
where
(
x
3
)
(
y
)
(
'
Use these indices to get the elements that satisfy the condition:
'
)
(
x
[
y
]
)
The output is:
我们的数组是:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Index of elements greater than 3:
(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))
Use these indices to get the elements that satisfy the condition:
[4. 5. 6. 7. 8.]
numpy.extract()
The numpy.extract() function extracts elements from an array based on a condition and returns the elements that satisfy it.
Example
import
numpy
as
np
x
=
np
.
arange
(
)
.
reshape
(
3
,
3
)
(
'
Our array is:
'
)
(
x
)
Define a condition to select even elements
condition
=
np
.
mod
(
x
,
2
)
==
0
(
'
Conditional values of the elements:
'
)
(
condition
)
(
'
Extract elements using the condition:
'
)
(
np
.
extract
(
condition
,
x
)
)
The output is:
我们的数组是:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
By the element's condition value:
[[ True False True]
[False True False]
[ True False True]]
Use condition to extract elements:
[0. 2. 4. 6. 8.]