1
votes

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.

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. So i.e. a float of 0.1 would return true, 0.4 false.

How would I tackle this?

2
Are you planning to use the ufunc functionality of logical_and (i.e. logical_and.accumulate(), .reduce(), .at() . . . )? Or just the basic function? - Daniel F
I did not plan to do it, is it needed? - Luuc
Probably not, but I wanted to make sure, as the built-in numpy function (np.isclose) is not a ufunc and can't do the extra things logical_and can. - Daniel F

2 Answers

1
votes

I think what you want is 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.

0
votes

Does the question require 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. @Daniel F 's use of isclose() is an elegant answer to this.

# 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)`.

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

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