10

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]
bkcollection
  • 913
  • 1
  • 12
  • 35
  • Possible duplicate of [Combining logic statements AND in numpy array](http://stackoverflow.com/questions/21996661/combining-logic-statements-and-in-numpy-array) – Moberg Feb 09 '17 at 07:44

3 Answers3

18

Try this,

(c > 2) & (c < 5)

Result

array([False,  True,  True, False, False], dtype=bool)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
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)

Community
  • 1
  • 1
Luke
  • 5,329
  • 2
  • 29
  • 34
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]
Jarvis
  • 8,494
  • 3
  • 27
  • 58