1.5 Comparison operators
In Expressions, you learned that Python has arithmetic operators: +, /, - and * and that expressions such as 5 + 2 evaluate to a value (in this case the number 7).
Python also has what are called comparison operators, these are:
!= not equal
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Expressions involving these operators always evaluate to a Boolean value, that is True or False. Here are some examples:
2 = = 2 evaluates to True
2 + 2 = = 5 evaluates to False
2 != 1 + 1 evaluates to False
45 < 50 evaluates to True
20 > 30 evaluates to False
100 <= 100 evaluates to True
101 >= 100 evaluates to True
The comparison operators can be used with other types of data, not just numbers. Used with strings they compare using alphabetical order. For example:
'aardvark' < 'zebra' evaluates to True
In Calculating over columns you saw that when applied to whole columns, the arithmetic operators did the calculations row by row. Similarly, an expression like df['Country'] >= 'K' will compare the country names, row by row, against the string 'K' and record whether the result is True or False in a series like this:
Name: Country, dtype: bool
If such an expression is put within square brackets immediately after a dataframe’s name, a new dataframe is obtained with only those rows where the result is True. So:
df[df['Country'] >= 'K']
returns a new dataframe with all the columns of df but with only the rows corresponding to countries starting with K or a letter later in the alphabet.
As another example, to see the data for countries with over 80 million inhabitants, the following code will return and display a new dataframe with all the columns of df but with only the rows where it is True that the value in the 'Population (1000s)' column is greater than 80000:
df[df['Population (1000s)'] > 80000]
|Country||Population (1000s)||TB deaths|
|185||United States of America||320051||490|
Exercise 2 Comparison operators
You are ready to complete Exercise 2 in the Exercise notebook 2.
Remember to run the existing code in the notebook before you start the exercise. When you’ve completed the exercise, save the notebook.