Numpy 排序,条件筛选函数

 
 

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() 用于对多个序列进行排序。把它想象成对电子表格进行排序,每一列代表一个序列,排序时优先照顾靠后的列。

 
import 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 ('
') 
print ('使用这个索引来获取排序后的数据:') 
print ([nm[i]  +  ", "  + dv[i]  for i in ind])
 
 
 
 
import 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 ('
') 
print ('使用这个索引来获取排序后的数据:') 
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))
 
 
 
 
 
 
 
我们的数组是:
[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]
按元素的条件值:
[[ True False  True]
 [False  True False]
 [ True False  True]]
使用条件提取元素:
[ 0.  2.  4.  6.  8.]
 
 
 
原文地址:https://www.cnblogs.com/DaLinY/p/920a03b7a3df557ec5b83f70985a4b53.html