Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform element-wise Boolean operations on NumPy arrays [duplicate]

For example, I would like to create a mask that masks elements with value between 40 and 60:

foo = np.asanyarray(range(100)) mask = (foo < 40).__or__(foo > 60) 

Which just looks ugly. I can't write

(foo < 40) or (foo > 60) 

because I end up with:

  ValueError Traceback (most recent call last)   ...   ----> 1 (foo < 40) or (foo > 60)   ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

Is there a canonical way of doing element-wise Boolean operations on NumPy arrays with good looking code?

like image 437
jb. Avatar asked Dec 25 '11 23:12

jb.


People also ask

How do you make a boolean Numpy array?

A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.

Is element-wise operation possible in Numpy?

Addition, subtraction, multiplication, and division of arguments(NumPy arrays) element-wise. First array elements raised to powers from second array, element-wise. Return element-wise remainder of division.

How do I add two Numpy arrays in element-wise?

To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are​ not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.

What does [: :] mean on Numpy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])


1 Answers

Try this:

mask = (foo < 40) | (foo > 60) 

Note: the __or__ method in an object overloads the bitwise or operator (|), not the Boolean or operator.

like image 125
jcollado Avatar answered Sep 21 '22 12:09

jcollado