A boolean value is either true or false. It is named after the British mathematician, George Boole, who first formulated Boolean algebra. This is the basis of all modern computer logic.
In Python, the two Boolean values are True and False (the capitalization must be exactly as shown), and the Python type is bool.
type(True)
bool
type(TRUE)
NameError: name 'TRUE' is not defined
A Boolean expression is an expression that evaluates the input and produces a result which is a Boolean value. For example, the operator == tests if two values are equal. It produces (or yields) a Boolean value:
Usually, boolean expressions contain "comparison" (or "relational") operators.
Here are six common comparison operators which all produce a bool result:
x == y # Produces True if ... x is equal to y
x != y # ... x is not equal to y
x > y # ... x is greater than y
x < y # ... x is less than y
x >= y # ... x is greater than or equal to y
x <= y # ... x is less than or equal to y
There are three logical operators, and, or, and not, that allow us to build more complex Boolean expressions from simpler Boolean expressions. The meaning of these operators is similar to their meaning in English. For example, x > 0 and x < 10 produces True only if x is greater than 0 and at the same time, x is less than 10.
n % 2 == 0 or n % 3 == 0 is True if either of the conditions is True, that is, if the number n is divisible by 2 or it is divisible by 3. (What do you think happens if n is divisible by both 2 and by 3 at the same time? Will the expression yield True or False? Try it in your Python interpreter.)
Finally, the not operator negates a Boolean value, so not (x > y) is True if (x > y) is False, that is, if x is less than or equal to y.
The expression on the left of the or operator is evaluated first: if the result is True, Python does not (and need not) evaluate the expression on the right — this is called short-circuit evaluation. Similarly, for the and operator, if the expression on the left yields False, Python does not evaluate the expression on the right.
This avoids unnecessary evaluations.
#Boolean Example
x = 10
y = 1
(3 > y) and (x < 20)
True
We know we can apply most mathematical functions and they'll be applied element-wise across numpy arrays. Like this:
import numpy as np
x = np.array([4,2,3])
y = np.array([1,5,6])
x + y
array([5, 7, 9])
However, often we may want to evaluate across multiple np.arrays to look for the position where both elements are True.
# With LISTS:
mylist1 = [True, True, False]
mylist2 = [False, True, True]
mylist1 and mylist2
#This will simply return the second list.
[False, True, True]
#Now we'll convert to numpy arrays and try again:
np.array(mylist1) and np.array(mylist2)
'''
this will give an error, since it is trying to determine a single "true" or "false" for the whole array,
and unlike lists (which are "True" by virtue of being non-empty) they have no default "truth value."
'''
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
So to write boolean expressions with numpy arrays, we have two options. Technically, you can use a bitwise operator (i.e., &, |). Computer scientists among you might argue that this isn't entirely appropriate, but it works, as shown below:
np.array(mylist1) & np.array(mylist2)
array([False, True, False])
The other alternative (and the "technically correct" way of evalutating) is to use numpy's "logical_and" function:
np.logical_and(np.array(mylist1), np.array(mylist2))
array([False, True, False])
Let's start by applying a boolean expression to a made-up numpy array:
A = np.array([4, 7, 3, 4, 2, 8])
A == 4
array([ True, False, False, True, False, False])
Now we'll apply those boolean values to *index* an entirely different array. We will index an array, B, in the following example by using a Boolean mask. It is called "fancy indexing" if arrays are indexed by passing an array of indices to access multiple array elements at once.
B = np.array([1,2,3,4,5,6])
B[A == 4] # Returns elements of B at index values from A where those values are equal to 4.
array([1, 4])
Do you think this will work if the arrays are of different lengths? Try it yourself first.
C = np.array([1,2,3,4,5,6,7]) # doesn't when array to be indexed is longer than the mask
C[A == 4]
IndexError: boolean index did not match indexed array along dimension 0; dimension is 7 but corresponding boolean dimension is 6
C = np.array([1,2,3,4]) # nor when array to be indexed is shorter than the mask.
C[A == 4]
IndexError: boolean index did not match indexed array along dimension 0; dimension is 4 but corresponding boolean dimension is 6
After using boolean operations to find elements matching some criteria, we may want to replace those values. We can do this like so:
B[A == 4] = 100
B
array([100, 2, 3, 100, 5, 6])
Notice this permanently changes the variable "B". Be careful to make a copy of your variable in case you don't wish to overwrite it! (like this: np.copy(var)).