NumPy - 排序、搜尋和計數函式



NumPy 提供了各種用於對陣列中的元素進行排序、搜尋和計數的函式。這些函式對於資料操作和分析非常有用。

NumPy 提供了幾種排序演算法,每種演算法都有其自身的特點。以下是三種常見排序演算法的比較:

kind 速度 最壞情況 工作空間 穩定性
'quicksort' 1 O(n^2) 0
'mergesort' 2 O(n*log(n)) ~n/2
'heapsort' 3 O(n*log(n)) 0

numpy.sort() 函式

sort() 函式返回輸入陣列的排序副本。它可以沿任何指定的軸對陣列進行排序,並支援不同的排序演算法。以下是語法:

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

其中,

序號 引數和描述
1

a

要排序的陣列

2

axis

要排序的陣列的軸。如果為 None,則陣列將被展平,並在最後一個軸上排序

3

kind

預設為 quicksort

4

order

如果陣列包含欄位,則要排序的欄位的順序

示例

在以下示例中,我們分別使用預設方式和沿特定軸對二維 NumPy 陣列進行排序。我們還演示瞭如何根據特定欄位(例如“name”)對結構化陣列進行排序:

import numpy as np  

# Create a 2D array
a = np.array([[3, 7], [9, 1]])

print("Our array is:",a)

# Default sort
print("Applying sort() function:",np.sort(a))

# Sort along axis 0
print("Sort along axis 0:",np.sort(a, axis=0))

# Order parameter in 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:",a)

print("Order by name:",np.sort(a, order='name'))

它將產生以下輸出:

Our array is:
[[3 7]
 [9 1]]

Applying sort() function:
[[3 7]
 [1 9]]

Sort along axis 0:
[[3 1]
 [9 7]]

Our array is:
[('raju', 21) ('anil', 25) ('ravi', 17) ('amar', 27)]

Order by name:
[('amar', 27) ('anil', 25) ('raju', 21) ('ravi', 17)]

numpy.argsort() 函式

numpy.argsort() 函式對輸入陣列沿給定軸並使用指定的排序型別進行間接排序,並返回資料索引的陣列。此索引陣列用於構造排序陣列。

示例

在此示例中,我們使用 argsort() 函式檢索索引,即排序元素在原始陣列中的位置。使用這些索引,您可以重建排序陣列:

import numpy as np 

# Create an array
x = np.array([3, 1, 2])

print("Our array is:",x)

# Get indices that would sort the array
y = np.argsort(x)

print("Applying argsort() to x:",y)

# Reconstruct the sorted array using the indices
print("Reconstruct original array in sorted order:",x[y])

# Reconstruct the original array using a loop
print("Reconstruct the original array using loop:")
for i in y:
   print(x[i], end=' ')

它將產生以下輸出:

Our array is:
[3 1 2]

Applying argsort() to x:
[1 2 0]

Reconstruct original array in sorted order:
[1 2 3]

Reconstruct the original array using loop:
1 2 3

numpy.lexsort() 函式

NumPy lexort() 函式使用一系列鍵執行間接排序。鍵可以看作電子表格中的列。該函式返回一個索引陣列,可以使用它來獲取排序資料。請注意,最後一個鍵恰好是排序的主鍵。

示例

在此示例中,我們使用 np.lexsort() 函式根據多個鍵對資料集進行排序,其中最後一個鍵“nm”是主要排序標準。然後使用排序索引透過組合名稱和相應的欄位來顯示排序資料:

import numpy as np 

# Define keys
nm = ('raju', 'anil', 'ravi', 'amar') 
dv = ('f.y.', 's.y.', 's.y.', 'f.y.') 

# Get indices for sorted order
ind = np.lexsort((dv, nm))

print("Applying lexsort() function:",ind)

# Use indices to get sorted data
print("Use this index to get sorted data:",[nm[i] + ", " + dv[i] for i in ind]) 

它將產生以下輸出:

Applying lexsort() function:
[3 1 0 2]

Use this index to get sorted data:
['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']
NumPy 提供了用於查詢最大值、最小值和非零元素以及滿足條件的元素的索引的函式。

numpy.argmax() 和 numpy.argmin() 函式

NumPy argmax() 和 argmin() 函式分別返回沿給定軸的最大和最小元素的索引。

示例

在此示例中,我們使用 np.argmax() 和 np.argmin() 函式查詢二維陣列中最大值和最小值的索引,包括展平陣列和沿特定軸的情況:

import numpy as np 

# Create a 2D array
a = np.array([[30, 40, 70], [80, 20, 10], [50, 90, 60]])

print("Our array is:",a)

# Apply argmax() function
print("Applying argmax() function:",np.argmax(a))

# Index of maximum number in flattened array
print("Index of maximum number in flattened array:",a.flatten())

# Array containing indices of maximum along axis 0
print("Array containing indices of maximum along axis 0:")
maxindex = np.argmax(a, axis=0)
print(maxindex)


# Array containing indices of maximum along axis 1
print("Array containing indices of maximum along axis 1:")
maxindex = np.argmax(a, axis=1)
print(maxindex)

# Apply argmin() function
print("Applying argmin() function:")
minindex = np.argmin(a)
print(minindex)

# Flattened array
print("Flattened array:",a.flatten()[minindex])

# Flattened array along axis 0
print("Flattened array along axis 0:")
minindex = np.argmin(a, axis=0)
print(minindex)

# Flattened array along axis 1
print("Flattened array along axis 1:")
minindex = np.argmin(a, axis=1)
print(minindex)

輸出包括這些極值的索引,演示瞭如何在陣列中訪問和解釋這些位置:

Our array is:
[[30 40 70]
 [80 20 10]
 [50 90 60]]

Applying argmax() function:
7

Index of maximum number in flattened array
[30 40 70 80 20 10 50 90 60]

Array containing indices of maximum along axis 0:
[1 2 0]

Array containing indices of maximum along axis 1:
[2 0 1]

Applying argmin() function:
5

Flattened array:
10

Flattened array along axis 0:
[0 1 1]

Flattened array along axis 1:
[0 2 0]

numpy.nonzero() 函式

numpy.nonzero() 函式返回輸入陣列中非零元素的索引。

示例

在下面的示例中,我們使用 nonzero() 函式檢索陣列“a”中非零元素的索引:

import numpy as np 
a = np.array([[30,40,0],[0,20,10],[50,0,60]]) 

print ('Our array is:',a)
print ('Applying nonzero() function:',np.nonzero (a))

它將產生以下輸出:

Our array is:
[[30 40 0]
 [ 0 20 10]
 [50 0 60]]

Applying nonzero() function:
(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))

numpy.where() 函式

where() 函式返回輸入陣列中滿足給定條件的元素的索引,如下面的示例所示:

import numpy as np 
x = np.arange(9.).reshape(3, 3) 

print ('Our array is:',x)  

print ('Indices of elements > 3')
y = np.where(x > 3) 
print (y)  

print ('Use these indices to get elements satisfying the condition',x[y])

它將產生以下輸出:

Our array is:
[[ 0. 1. 2.]
 [ 3. 4. 5.]
 [ 6. 7. 8.]]

Indices of elements > 3
(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))

Use these indices to get elements satisfying the condition
[ 4. 5. 6. 7. 8.]

numpy.extract() 函式

extract() 函式返回滿足任何條件的元素,如下面的示例所示:

import numpy as np 
x = np.arange(9.).reshape(3, 3) 

print ('Our array is:',x)  

# define a condition 
condition = np.mod(x,2) == 0 

print ('Element-wise value of condition',condition)

print ('Extract elements using condition',np.extract(condition, x))

它將產生以下輸出:

Our array is:
[[ 0. 1. 2.]
 [ 3. 4. 5.]
 [ 6. 7. 8.]]

Element-wise value of condition
[[ True False True]
 [False True False]
 [ True False True]]

Extract elements using condition
[ 0. 2. 4. 6. 8.]
廣告