2
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?

1
  • 4
    Try (A<7) & (A>3) (for example). Commented Feb 20, 2019 at 13:09

5 Answers 5

3

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])
Sign up to request clarification or add additional context in comments.

Comments

2

Choose x value and then :

x = 3
np.logical_and(x<A, A<7)

Comments

1

Just use a list comprehension:

x = 3
bools = [i<7 and i> x for i in A]

Comments

1

You could use numpy.logical_and for that task, example:

import numpy as np
A = np.arange(0,20,1)
B = np.logical_and(3<A,A<7)
print(B)

Output:

[False False False False  True  True  True False False False False False
 False False False False False False False False]

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.