简体   繁体   English

如何用边距做numpy logical_and?

[英]How to do numpy logical_and with a margin?

I have two numpy vector arrays, one contains binary values so either 1 or 0 and the other float values so anything in between 0 and 1.我有两个 numpy 向量数组,一个包含二进制值,所以要么是 1 要么是 0,另一个是浮点值,所以任何介于 0 和 1 之间的值。

I want to use the numpy.logical_and operator and have it return true if the binary value is in the range of the float plus or minus 0.2.我想使用numpy.logical_and运算符,如果二进制值在浮点数正负 0.2 的范围内,则返回 true。 So ie a float of 0.1 would return true, 0.4 false.因此,即 0.1 的浮点数将返回 true,0.4 false。

How would I tackle this?我将如何解决这个问题?

I think what you want is np.isclose .我想你想要的是np.isclose In this case implementation would be:在这种情况下,实现将是:

bin_arr = np.random.randint(2, size = 100)
float_arr = np.random.rand(100)
out = np.isclose(bin_arr.astype(float), float_arr, atol = .2)

Note that while logical_and is a ufunc (Universal Function) with extended functionality, np.isclose is not.请注意,虽然logical_andufunc (通用功能)具有扩展功能, np.isclose不是。

Does the question require True if (float_arr less than 0.2) AND (bin_arr > 0) .问题是否需要True if (float_arr less than 0.2) AND (bin_arr > 0) Which does need the use of logical and.这确实需要使用逻辑和。

Or True if abs(float_arr - bin_arr) <= 0.2 which doesn't.或者True if abs(float_arr - bin_arr) <= 0.2没有。 @Daniel F 's use of isclose() is an elegant answer to this. @Daniel F对 isclose() 的使用是对此的优雅回答。

# Set up some data
np.random.seed(0)  # Make it repeatable.
bin_arr = np.random.randint(2, size = 20)
float_arr = np.random.rand(20) 
bin_arr, float_arr

# (array([0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]),
# array([0.79172504, 0.52889492, 0.56804456, 0.92559664, 0.07103606,
#        0.0871293 , 0.0202184 , 0.83261985, 0.77815675, 0.87001215,
#        0.97861834, 0.79915856, 0.46147936, 0.78052918, 0.11827443,
#        0.63992102, 0.14335329, 0.94466892, 0.52184832, 0.41466194]))

True if (float_arr less than 0.2) AND (bin_arr > 0)`.如果 (float_arr 小于 0.2) AND (bin_arr > 0)` 为真。

np.logical_and( float_arr<=0.2, bin_arr)
# array([False, False, False, False,  True,  True,  True, False, False,
#        False, False, False, False, False, False, False, False, False,
#        False, False])

True if abs(float_arr - bin_arr) <= 0.2如果 abs(float_arr - bin_arr) <= 0.2,则为真

np.abs(float_arr - bin_arr)<=0.2
# array([False, False, False, False, False, False, False,  True, False,
#        True,  True, False, False, False,  True, False,  True, False,
#        False, False])

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

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