在Numpy中使用np.logical_and进行子选择

时间:2016-05-24 09:13:31

标签: python numpy

我绘制(x,y)图表,并且当x从A到B的范围大于C时,想要返回True("在区间中存在x,使得y(x)> C) 。下面的代码不起作用。我该怎么办?

d_for_hours=density[np.logical_and(y>C,x>=A, x <=B)].all()

示例性输出:

对于C = 0.02且A = 9且B = 13,输出应为True

对于C = 0.05且A = 9且B = 13,输出应为False

enter image description here

1 个答案:

答案 0 :(得分:1)

您希望使用any而不是all来检查y是否有高于C的任何值。在此之前,您需要将y限制为符合条件的x索引(AB之间):

# create data
x = np.array(range(20))
y = np.array(19 * [0] + [1])

(y[np.logical_and(x>=9, x<=13)] >= 0.05).any()  # False
(y[np.logical_and(x>=9, x<=20)] >= 0.05).any()  # True
相关问题