Each element of the first object is compared with the corresponding element of the second object. The result of comparison is a Boolean value.
Let's understand these operators with the help of an example. Let's create two NumPy arrays containing returns from two stocks over the past five days.
1>>> import numpy as np
2>>> stock_A = np.array([10, 8, 9, 11, 12])
3>>> stock_B = np.array([8, 11, 10, 10, 12])
4>>> stock_A
5array([10, 8, 9, 11, 12])
6>>> stock_B
7array([ 8, 11, 10, 10, 12])
8>>>
9
Greater Than (>
)
The greater than (>)
symbol checks if each element of the first object is greater than the corresponding element of the second object. The result will be an object with logical values (TRUE or FALSE) depending on whether the condition is true or not.
In the following code, we compare if Stock A's returns are higher than Stock B's returns
1>>> stock_A > stock_B
2array([ True, False, False, True, False], dtype=bool)
3>>>
4
As you can see, Stock A's returns were higher than Stock B on day 1 (10 > 8
) and day 4 (11 > 10
). So, for these days, the resulting array contains TRUE, while for the rest of the days, it is FALSE. Specially observe the last day where the returns were same for both the stocks (12 and 12). Since the condition was exclusively checking for returns being greater, the condition is FALSE here.
Less Than (<
)
The less than (<)
symbol checks if each element of the first array is less than the corresponding element of the second array. This is just the opposite of the 'greater than' operator.
1>>> stock_A < stock_B
2array([False, True, True, False, False], dtype=bool)
3>>>
4
Equal (==
)
The equal (==)
operator checks if each element of the first array is equal to the corresponding element of the second array. In our arrays, this condition meets only for the returns on the last day (12 == 12) as shown below:
1>>> stock_A == stock_B
2array([False, False, False, False, True], dtype=bool)
3>>>
4
Not Equal To (!=
)
The Not Equal (!=)
operator checks if each element of the first array is unequal to the corresponding element of the second array.
1>>> stock_A != stock_B
2array([ True, True, True, True, False], dtype=bool)
3>>>
4
Greater Than Equal To (>=
)
The Greater Than Equal To (>=)
operator checks if each element of the first array is greater than or equal to the corresponding element of the second array.
1>>> stock_A >= stock_B
2array([ True, False, False, True, True], dtype=bool)
3>>>
4
Compare this with the Greater Than (>)
operator. Everything else is same, just the last element now returns TRUE (because of the equal to condition).
Less Than Equal To (<=
)
The Less Than Equal To (<=)
operator checks if each element of the first array is less than or equal to the corresponding element of the second array.
1>>> stock_A <= stock_B
2array([False, True, True, False, True], dtype=bool)
3>>>
4