A = np.arange(0,20,1)
A<7
The above code will return a boolean array where its elements are true when A<7 and otherwise false. How do I get such a boolean array for x < A < 7?
If your x = 3, then:
a = np.arange(0,20,1)
a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19])
(a>3) & (a<7)
array([False, False, False, False, True, True, True, False, False,
False, False, False, False, False, False, False, False, False,
False, False])
If you want an or condition you can replace & with |:
(a<3) | (a>7) #Less than 3 or greater than 7
array([ True, True, True, False, False, False, False, False, True,
True, True, True, True, True, True, True, True, True,
True, True])
import timeit
A = np.arange(0, 20, 1)
# print(A)
x = 3
def fun():
return [x < i < 7 for i in A]
def fun2():
return (A < 7) & (A > 3)
def fun3():
return np.logical_and(x < A, A < 7)
def fun4():
return [i < 7 and i > x for i in A]
print('fun()', timeit.timeit('fun()', number=10000, globals=globals()))
print('fun2()', timeit.timeit('fun2()', number=10000, globals=globals()))
print('fun3()', timeit.timeit('fun3()', number=10000, globals=globals()))
print('fun4()', timeit.timeit('fun4()', number=10000, globals=globals()))
output:
execution time(in seconds):
fun() 0.055701432000205386
fun2() 0.016561345997615717
fun3() 0.016588653001235798
fun4() 0.0446821750010713
(A<7) & (A>3)(for example).