简体   繁体   English

如何检查向量的元素是否位于 Numpy 中的两个向量之间?

[英]How to check if elements of a vector lies between two vectors in Numpy?

Let's say A and B are given vectors and the aim is to check which elements of Y lie between A and B. For example:假设AB被赋予向量,目的是检查Y哪些元素位于 A 和 B 之间。例如:

A=np.array([1,2,3,4])
B=np.array([10,20,30,40])
Y=np.array([8,15,0,50])

The expected output should look like: [1,1,0,0] where the elements are not bool type so I can find out the number of true values, using np.sum()预期输出应如下所示: [1,1,0,0]其中元素不是 bool 类型,因此我可以使用np.sum()找出真实值的数量

You can so both comparisons and take the elementwise and您可以进行比较并进行元素and

(A < Y) & (Y < B)

A np.sum() will work regardless of them being boolean.无论它们是布尔值, np.sum()都可以工作。 When in doubt, just cast to int using如有疑问,只需使用 int 强制转换

X.astype(int)

It's as simple as就这么简单

np.logical_and(A <= Y, Y <= B).astype(int)

But you can also sum a logical vector, numpy will handle the conversion under the hood.但是你也可以对一个逻辑向量求和,numpy 将处理引擎盖下的转换。

In [1]: np.sum(np.logical_and(A <= Y, Y <= B).astype(int)) == np.sum(np.logical_and(A <= Y, Y <= B))
Out[1]: True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM