Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: numpy array larger and smaller than a value

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]
like image 696
bkcollection Avatar asked Feb 09 '17 07:02

bkcollection


People also ask

How do I compare values in two NumPy arrays?

Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.

Can NumPy arrays be resized?

With the help of Numpy numpy. resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.

Can NumPy arrays have more than 2 dimensions?

In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.


3 Answers

Try this,

(c > 2) & (c < 5)

Result

array([False,  True,  True, False, False], dtype=bool)
like image 89
Rahul K P Avatar answered Sep 19 '22 15:09

Rahul K P


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)

like image 29
Luke Avatar answered Sep 18 '22 15:09

Luke


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]
like image 39
Jarvis Avatar answered Sep 20 '22 15:09

Jarvis