简体   繁体   中英

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:

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()

You can so both comparisons and take the elementwise and

(A < Y) & (Y < B)

A np.sum() will work regardless of them being boolean. When in doubt, just cast to int using

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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