Relational and Logical Operators with Pandas Series

Let's find out how to use relational operators to compare the values of a pandas series.

We'll cover the following

Try it yourself

Try executing the code below to see the result.

Press + to interact
import pandas as pd
nums = pd.Series([1, 2, 3, 4, 5, 6])
print(nums[(nums > 2) and (nums < 5)])

Explanation

The result of nums > 2 is the series of Boolean values listed below:

In [1]: nums>2
Out[1]:
0 False
1 False
2 True
3 True
4 True
5 True
dtype: bool

We can use this Boolean series to select parts of other series that are the same size, including, of course, nums. The process, which is shown below, is known as Boolean inexing.

In [2]: nums[nums>2]
Out[2]:
2 3
3 4
4 5
5 6
dtype: int64

We can combine two or more Boolean series to create a more complex condition using Python’s logical operators and, or, and not. This is what we’re doing in the teaser (nums > 2) and (nums < 5). However, these Python logical operators will call the built-in Boolean function on nums > 2 and nums < 5.

Just like we saw in the first puzzle, Rectified, this will raise an error. To solve this, pandas and NumPy use the bitwise operators listed below:

  • & instead of and
  • | instead of or
  • ~ instead of not

In the example below, the following code will pick all the values in a series that are not nan:

In [3]: s = pd.Series([1, np.nan, 2])
In [4]: s[~pd.isnull(s)]
Out[4444]:
0 1.0
2 2.0
dtype: float64

To fix our teaser, we can replace the and with &.

Solution

Press + to interact
import pandas as pd
nums = pd.Series([1, 2, 3, 4, 5, 6])
print(nums[(nums > 2) & (nums < 5)])

Get hands-on with 1300+ tech skills courses.