numpy.sort()函数
该函数提供了多种排序功能,支持归并排序,堆排序,快速排序等多种排序算法
使用numpy.sort()方法的格式为:
numpy.sort(a,axis,kind,order)
a:要排序的数组
axis:沿着排序的轴,axis=0按照列排序,axis=1按照行排序。
kind:排序所用的算法,默认使用快速排序。常用的排序方法还有
quicksort:快速排序,速度最快,算法不具有稳定性
mergesort:归并排序,优点是具有稳定性,空间复杂度较高,一般外部排序时才会考虑
heapsort:堆排序,优点是堆排序在最坏的情况下,其时间复杂度也为O(nlogn),是一个既最高效率又最节省空间的排序方法
order:如果包含字段,则表示要排序的字段(比如按照数组中的某个元素项进行排序)
下面通过一个实例来具体了解numpy.sort()函数的用法
假设我们有一组用户信息,包含用户的用户名以及用户的年龄,我们按照用户的年龄来进行排序
?
运行结果:
[(b'adm', 19) (b'ade', 23) (b'wan', 23)]
Process finished with exit code 0
numpy.argsort()函数
numpy.argsort()函数返回的时从小到大的元素的索引
可以通过以下的实例更好的理解
使用argsort()方法返回索引并重构数组
?
运行结果:
返回从小到大的索引
[3 0 4 1 2]
以索引对原数组排序
[ 2 3 5 8 11]
重构原数组
2,3,5,8,11,
Process finished with exit code 0
numpy.lexsort()函数
numpy.sort()函数可对于多个序列进行排序,例如我们在比较成绩的时候先比较总成绩,由后列到前列的优先顺序进行比较,这时就用到了lexsort()方法
?
运行结果:
使用这个索引来获取排序后的数据:
['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']
Process finished with exit code 0
numpy.partition()函数
numpy.partition()叫做分区排序,可以制定一个数来对数组进行分区。
格式如下:
?
实例:实现将数组中比7小的元素放到前面,比7大的放后面
?
运行结果:
[ 0 1 2 3 7 9 13 23]
Process finished with exit code 0
实例:实现将数组中比7小的元素放到前面,比10大的放后面,7-10之间的元素放中间
partition分区排序
?
运行结果
[ 1 0 2 3 5 6 7 9 10 12 13 23 27]
[ 0 1 2 6 5 3 7 9 10 12 23 13 27]
Process finished with exit code 0
注意:(7,10)中10的位置,数值不能超过数组长度。
numpy.nonzero()函数
返回输入数组中非零元素的索引
?
运行结果:
我们的数组是:
[[30 40 0]
[ 0 20 10]
[50 0 60]]
调用 nonzero() 函数:
(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))
Process finished with exit code 0
numpy.where()函数
返回满足输入条件的索引
?
运行结果:
(array([6, 7, 8], dtype=int64),)
利用索引得到数组中的元素
[23 13 27]
Process finished with exit code 0
numpy.extract()函数
numpy.extract()函数实现的是返回自定义条件的元素
?
运行结果:
[9 2 6]
Process finished with exit code 0
其它排序函数
numpy.argmax() 和 numpy.argmin()函数分别沿给定轴返回最大和最小元素的索引。numpy.sort_complex(a)函数实现对复数按照先实部后虚部的顺序进行排序。numpy.argpartition(a, kth[, axis, kind, order])函数实现通过指定关键字沿着指定的轴对数组进行分区。
下面举一个复数排序的例子:
?
运行结果:
[1.+2.j 2.-1.j 3.-3.j 3.-2.j 3.+5.j]
Process finished with exit code 0
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/supershuai/p/12221362.html