365Tools
    发布时间:2024-03-04 20:30:01
NumPy 提供了多种排序函数, 这些排序函数可以实现不同的排序算法。| 种类 | 速度 | 最坏复杂度 | 工作空间 | 稳定性 | 
|---|---|---|---|---|
| quicksort(快速排序) | 1 | O(n^2) | 0 | 不稳定 | 
| mergesort(归并排序) | 2 | O(n * log(n)) | ~n/2 | 稳定 | 
| heapsort(堆排序) | 3 | O(n * log(n)) | 0 | 不稳定 | 
numpy.sort(a, axis, kind, order)
参数说明:
import numpy as np 
a = np.array([[3,7],[9,1]]) 
print('a数组是:')
print(a)
#调用sort()函数
print(np.sort(a))
#按列排序:
print(np.sort(a, axis = 0))
#设置在sort函数中排序字段
dt = np.dtype([('name',  'S10'),('age',  int)])
a = np.array([("raju",21),("anil",25),("ravi",  17),  ("amar",27)], dtype = dt) 
#再次打印a数组
print(a)
#按name字段排序
print(np.sort(a, order = 'name'))
输出结果:
我们的数组是: [[3 7] [9 1]] 调用sort()函数: [[3 7] [1 9]] 按列排序: [[3 1] [9 7]] 再次打印a数组: [(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)]
import numpy as np 
a = np.array([90, 29, 89, 12]) 
print("原数组",a) 
sort_ind = np.argsort(a) 
print("打印排序元素索引值",sort_ind) 
#使用索引数组对原数组排序
sort_a = a[sort_ind] 
print("打印排序数组") 
for i in sort_ind: 
    print(a[i],end = " ")  
输出结果:
原数组: [90 29 89 12] 打印排序元素的索引数组: [3 1 2 0] 打印排序数组: 12 29 89 90
import numpy as np 
a = np.array(['a','b','c','d','e']) 
b = np.array([12, 90, 380, 12, 211]) 
ind = np.lexsort((a,b)) 
#打印排序元素的索引数组
print(ind) 
#使用索引数组对数组进行排序
for i in ind: 
    print(a[i],b[i])  
输出结果:
打印排序元素的索引数组: [0 3 1 4 2] 使用索引数组对原数组进行排序: a 12 d 12 b 90 e 211 c 380
import numpy as np 
 
b = np.array([12, 90, 380, 12, 211]) 
 
print("原数组b",b) 
 
print("打印非0元素的索引位置") 
 
print(b.nonzero())  
原数组b [ 12 90 380 12 211] 打印非0元素的索引位置 (array([0, 1, 2, 3, 4]),)
import numpy as np b = np.array([12, 90, 380, 12, 211]) print(np.where(b>12)) c = np.array([[20, 24],[21, 23]]) print(np.where(c>20))
返回满足条件的索引数组 (array([1, 2, 4]),) (array([0, 1, 1]), array([1, 0, 1]))
import numpy as np x = np.arange(9.).reshape(3, 3) 打印数组x:' print(x) #设置条件选择偶数元素 condition = np.mod(x,2)== 0 #输出布尔值数组 print(condition) #按condition提取满足条件的元素值 print np.extract(condition, x)输出结果:
a数组是: [[0. 1. 2.] [3. 4. 5.] [6. 7. 8.]] 输出布尔值数组: [[ True False True] [False True False] [ True False True]] 按条件提取元素: [0. 2. 4. 6. 8.]
import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) #a数组 print (a) #argmax() 函数 print (np.argmax(a)) #将数组以一维展开 print (a.flatten()) #沿轴 0 的最大值索引: maxindex = np.argmax(a, axis = 0) print (maxindex) #沿轴 1 的最大值索引 maxindex = np.argmax(a, axis = 1) print (maxindex)输出结果:
数组a: [[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]
import numpy as np
b= np.array([[3,4,7],[8,2,1],[5,9,6]]) 
print  ('数组b:')
print (b) 
#调用 argmin()函数
minindex = np.argmin(b) 
print (minindex)
#展开数组中的最小值:
print (b.flatten()[minindex])
#沿轴 0 的最小值索引:
minindex = np.argmin(b, axis =  0) 
print (minindex)
#沿轴 1 的最小值索引:
minindex = np.argmin(b, axis =  1) 
print (minindex)
输出结果:
数组b: [[3 4 7] [8 2 1] [5 9 6]] 返回最小索引值: 5 #展开数组中的最小值: 1 #沿轴 0 的最小值索引: [0 1 1] #沿轴 1 的最小值索引: [0 2 0]