How to compare elements of a series by Python list using pandas series.gt() function?


By using pandas series.gt() function, we can apply the Greater Than condition to the elements of a series with list elements. The series.gt() method is used to apply the element-wise Greater Than comparison operation between two objects. The two objects are series and other (series, scalar of sequence).

Example 1

Given below is an example of how the gt() method will apply Greater Than condition between series and list. Here, we will see how the series.gt() method works for series and a list.

import pandas as pd
import numpy as np

# create pandas Series
s = pd.Series([9, 103, 18, 31, 92])

print("Series object:",s)

# apply gt() method using a list of integers
print("Output:")
print(s.gt(other=[26, 70, 38, 29, 59]))

Output

The output is given below −

Series object:
0    9
1    103
2    18
3    31
4    92
dtype: int64

Output:
0    False
1    True
2    False
3    True
4    True
dtype: bool

The first element in the series object 9 is compared with the first element of the list 26 (9 > 26) then the corresponding output will be represented in the resultant series object (False for this condition). In the same way, the remaining elements are also compared.

Example 2

Let’s take another pandas series object and apply the Greater Than condition with a list of integers.

import pandas as pd
import numpy as np

# create pandas Series
s = pd.Series([np.nan, 1, 84, 57, 21, 66,])

print("Series object:",s)

# apply gt() method using a list of integers by replacing missing values
print("Output:")
print(s.gt(other=[29, 11, 44, 43, 37, 32], fill_value=40))

Explanation

Here, we will replace the missing values by specifying integer value 40 to the fill_value parameter.

Output

The output is mentioned below −

Series object:
0    NaN
1    1.0
2    84.0
3    57.0
4    21.0
5    66.0
dtype: float64

Output:
0    True
1    False
2    True
3    True
4    False
5    True
dtype: bool

The gt() method successfully replaced the missing values by 40 and then compared the elements of two input objects(series and list).

Updated on: 07-Mar-2022

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements