numpy 基础相关

Numpy的逻辑运算

一、问题?

如果我们想要判断获取涨幅大于0.5一写区段?

二、逻辑运算

# 逻辑判断
temp > 0.5

# 赋值
temp[temp > 0.5] = 1

#如果小于2 为0否则保持不变
img = np.where(img < 2,  0,img)
img = np.where(img >253,  255,img)
img = np.where(np.logical_and(img >= 2, img <= 253), 128, img)

 

 

三、通用判断函数

  • np.all()
#判断stock_day_rise[0:2,0:5]是否全是上涨的
np.all(stock_day_rise[0:2,0:5] > 0)

 

  • np.unique()

返回新的数组的数值,不存在重复的值

#将序列中数值值唯一且不重复的值组成新的序列

change_int = stock_day_rise[0:2,0:5].astype(int)
np.unique(change_int)

 

四、np.where(三元运算符)

通过使用np.where能够进行更加复杂的运算

  • np.where()

 

np.where(temp > 0, 1, 0)

 

复合逻辑需要结合np.logical_and和np.logical_or使用

# 判断前四个股票前四天的涨跌幅 大于0.5并且小于1的,换为1,否则为0
# 判断前四个股票前四天的涨跌幅 大于0.5或者小于-0.5的,换为1,否则为0
np.where(np.logical_and(temp > 0.5, temp < 1), 1, 0)
np.where(np.logical_or(temp > 0.5, temp < -0.5), 1, 0)

 

五、numpy获取白色区域的最左上角和最右下角坐标

img = cv2.imread("/tmp/t1_1/01989_nose.png")

idx = np.where(img > 128)
print(idx)
left_x = min(idx[1])
left_y = min(idx[0])
right_x = max(idx[1])
right_y = max(idx[0])

print(left_x,left_y)
print(right_x,right_y)

 

 

 

 

 

 

 

 

 

 

posted on 2021-03-29 12:32  星河赵  阅读(77)  评论(0编辑  收藏  举报

导航