当前位置:K88软件开发文章中心编程语言PythonPython01 → 文章内容

NumPy 排序、条件刷选函数

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-11 13:39:25

o() 函数返回输入数组中非零元素的索引。实例import numpy as npa = np.array([[30,40,0],[0,20,10],[50,0,60]])print ('我们的数组是:')print (a)print ('\n')print ('调用 nonzero() 函数:')print (np.nonzero (a))输出结果为:我们的数组是:[[30 40 0] [ 0 20 10] [50 0 60]]调用 nonzero() 函数:(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))numpy.where()numpy.where() 函数返回输入数组中满足给定条件的元素的索引。实例import numpy as npx = np.arange(9.).reshape(3, 3)print ('我们的数组是:')print (x)print ( '大于 3 的元素的索引:')y = np.where(x > 3)print (y)print ('使用这些索引来获取满足条件的元素:')print (x[y])输出结果为:我们的数组是:[[0. 1. 2.] [3. 4. 5.] [6. 7. 8.]]大于 3 的元素的索引:(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))使用这些索引来获取满足条件的元素:[4. 5. 6. 7. 8.]numpy.extract()numpy.extract() 函数根据某个条件从数组中抽取元素,返回满条件的元素。实例import numpy as npx = np.arange(9.).reshape(3, 3)print ('我们的数组是:')print (x)





# 定义条件, 选择偶数元素condition = np.mod(x,2) == 0print ('按元素的条件值:')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.]

上一页  [1] [2] 


NumPy 排序、条件刷选函数