11

How to look for numbers that is between a range?

c = array[2,3,4,5,6]
>>> c>3
>>> array([False, False, True, True, True]

However, when I give c in between two numbers, it return error

>>> 2<c<5
>>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The desire output is

array([False, True, True, False, False]
1

3 Answers 3

19

Try this,

(c > 2) & (c < 5)

Result

array([False,  True,  True, False, False], dtype=bool)
Sign up to request clarification or add additional context in comments.

Comments

4

Python evaluates 2<c<5 as (2<c) and (c<5) which would be valid, except the and keyword doesn't work as we would want with numpy arrays. (It attempts to cast each array to a single boolean, and that behavior can't be overridden, as discussed here.) So for a vectorized and operation with numpy arrays you need to do this:

(2<c) & (c<5)

Comments

1

You can do something like this :

import numpy as np
c = np.array([2,3,4,5,6])
output = [(i and j) for i, j in zip(c>2, c<5)]

Output :

[False, True, True, False, False]

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.