1.6 Bitwise operators
To build more complicated expressions involving column comparisons, there are two bitwise operators.

The operator means ‘and’ and the | operator (vertical bar, not uppercase letter ‘i’) means ‘or’. So, for example the expression:
(df['Country'] >= 'Latvia') & (df['Country'] <= 'Sweden')
will evaluate to a series containing Boolean values where the values are only if the equivalent rows in the dataframe contain the countries ‘’ to ‘’, inclusive. However, the following expression which uses | (or) rather than & (and):
(df['Country'] >= 'Latvia') | (df['Country'] <= 'Sweden')
will evaluate to for all countries, because every country comes alphabetically after ‘’ (e.g. the ‘UK’) or before '' (e.g. ‘’).
Note the round brackets around each comparison. Without them you will get an error.
The whole expression with multiple comparisons has to be put within to get a dataframe with only those rows that match the condition.
As a further example, using different columns, it is relatively easy to find the rows in where '' is greater than and where '' are greater than 10000.
df[(df['Population (1000s)'] > 80000) & (df['TB deaths'] > 10000)]
| Country | Population (1000s) | TB deaths | |
|---|---|---|---|
| 13 | Bangladesh | 156595 | 80000 |
| 36 | China | 1393337 | 41000 |
| 58 | Ethiopia | 94101 | 30000 |
| 77 | India | 1252140 | 240000 |
| 78 | Indonesia | 249866 | 64000 |
| 124 | Nigeria | 173615 | 160000 |
| 128 | Pakistan | 182143 | 49000 |
| 134 | Philippines | 98394 | 27000 |
| 141 | Russian Federation | 142834 | 17000 |
| 190 | Viet Nam | 91680 | 17000 |
These expressions can get long and complicated, making it easy to miss a crucial round or square bracket. In those cases it is best to break up the expression into small steps. The previous example could also be written as:
population = df['Population (1000s)']
deaths = df['TB deaths']
df[(population > 80000) & (deaths > 10000)]
Exercise 3 Bitwise operators
Complete Exercise 3 in the Exercise notebook 2.
OpenLearn - Introduction and guidance
Except for third party materials and otherwise, this content is made available under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 Licence, full copyright detail can be found in the acknowledgements section. Please see full copyright statement for details.
