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?
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.
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.
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.
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.]])
Try this:
mask = (foo < 40) | (foo > 60)
Note: the __or__
method in an object overloads the bitwise or operator (|
), not the Boolean or
operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With