Numpy 排序,條件篩選函式
阿新 • • 發佈:2019-01-04
NumPy 排序、條件刷選函式
NumPy 提供了多種排序的方法。 這些排序函式實現不同的排序演算法,每個排序演算法的特徵在於執行速度,最壞情況效能,所需的工作空間和演算法的穩定性。 下表顯示了三種排序演算法的比較。
種類 | 速度 | 最壞情況 | 工作空間 | 穩定性 |
---|---|---|---|---|
'quicksort' (快速排序) |
1 | O(n^2) |
0 | 否 |
'mergesort' (歸併排序) |
2 | O(n*log(n)) |
~n/2 | 是 |
'heapsort' (堆排序) |
3 | O(n*log(n)) |
0 | 否 |
numpy.sort()
numpy.sort() 函式返回輸入陣列的排序副本。函式格式如下:
numpy.sort(a, axis, kind, order)
引數說明:
- a: 要排序的陣列
- axis: 沿著它排序陣列的軸,如果沒有陣列會被展開,沿著最後的軸排序, axis=0 按列排序,axis=1 按行排序
- kind: 預設為'quicksort'(快速排序)
- order: 如果陣列包含欄位,則是要排序的欄位
numpy.argsort()
numpy.argsort() 函式返回的是陣列值從小到大的索引值。
numpy.lexsort()
numpy.lexsort() 用於對多個序列進行排序。把它想象成對電子表格進行排序,每一列代表一個序列,排序時優先照顧靠後的列。
1 10 1import numpy as np nm = ('raju','anil','ravi','amar') dv = ('f.y.', 's.y.', 's.y.', 'f.y.') ind = np.lexsort((dv,nm)) print ('呼叫 lexsort() 函式:') print (ind) print ('\n') print ('使用這個索引來獲取排序後的資料:') print ([nm[i] + ", " + dv[i] for i in ind])
import numpy as np
2
3
nm = ('raju','anil','ravi','amar')
4
dv = ('f.y.', 's.y.', 's.y.', 'f.y.')
5
ind = np.lexsort((dv,nm))
6
print ('呼叫 lexsort() 函式:')
7
print (ind)
8
print ('\n')
9
print ('使用這個索引來獲取排序後的資料:')
10
print ([nm[i] + ", " + dv[i] for i in ind])
呼叫 lexsort() 函式: [3 1 0 2] 使用這個索引來獲取排序後的資料: ['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']
上面傳入 np.lexsort 的是一個tuple,排序時首先排 nm,順序為:amar、anil、raju、ravi 。綜上排序結果為 [3 1 0 2]。
msort、sort_complex、partition、argpartition
函式 | 描述 |
---|---|
msort(a) | 陣列按第一個軸排序,返回排序後的陣列副本。np.msort(a) 相等於 np.sort(a, axis=0)。 |
sort_complex(a) | 對複數按照先實部後虛部的順序進行排序。 |
partition(a, kth[, axis, kind, order]) | 指定一個數,對陣列進行分割槽 |
argpartition(a, kth[, axis, kind, order]) | 可以通過關鍵字 kind 指定演算法沿著指定軸對陣列進行分割槽 |
numpy.argmax() 和 numpy.argmin()
numpy.argmax() 和 numpy.argmin()函式分別沿給定軸返回最大和最小元素的索引。
numpy.nonzero()
numpy.nonzero() 函式返回輸入陣列中非零元素的索引。
numpy.where()
numpy.where() 函式返回輸入陣列中滿足給定條件的元素的索引。
numpy.extract()
numpy.extract() 函式根據某個條件從陣列中抽取元素,返回滿條件的元素。
import numpy as np
x = np.arange(9.).reshape(3, 3)
print ('我們的陣列是:')
print (x)
# 定義條件, 選擇偶數元素
condition = np.mod(x,2) == 0
print ('按元素的條件值:')
print (condition)
print ('使用條件提取元素:')
print (np.extract(condition, x))
11
11
1
import numpy as np
2
3
x = np.arange(9.).reshape(3, 3)
4
print ('我們的陣列是:')
5
print (x)
6
# 定義條件, 選擇偶數元素
7
condition = np.mod(x,2) == 0
8
print ('按元素的條件值:')
9
print (condition)
10
print ('使用條件提取元素:')
11
print (np.extract(condition, x))
我們的陣列是: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] 按元素的條件值: [[ True False True] [False True False] [ True False True]] 使用條件提取元素: [ 0. 2. 4. 6. 8.]
來自為知筆記(Wiz)