您的位置:首页 > 编程语言 > Python开发

python numpy元素的区间查找

2017-12-12 15:58 435 查看
找了半天,以为numpy的where函数像matlab 的find函数一样好用,能够返回一个区间内的元素索引位置。结果没有。。(也可能是我没找到)

故自己写一个函数,找多维数组下的,在某个开区间的元素位置

import numpy as np
def find(arr,min,max):
pos_min = arr>min
pos_max =  arr<max
pos_rst = pos_min & pos_max
return np.where(pos_rst == True)#where的返回值刚好可以用[]来进行元素提取

a=np.arange(10).reshape(2,5)

pos=find(a,a>3,a<=7)
print(a[pos])#where的返回值刚好可以用[]来进行元素提取


改进版本,接近matlab语法

def find(arr,pos_min,pos_max):
#pos_min = arr>=min
#pos_max =  arr<max
pos_rst = pos_min & pos_max
return np.where(pos_rst == True)#where的返回值刚好可以用[]来进行元素提取


python的numpy where的真正用法,绕了一个大弯

pos=np.where( (a>=3) & (a<8)) #非常要注意这个括号 没有括号估计内部执行顺序不对,捣腾不出来的,具体原因可评论留言
print (a[pos])



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python numpy where