How to compare two Pandas Series Objects by Applying Greater Than Condition using gt() Function?

PandasServer Side ProgrammingProgramming

In the pandas series constructor, there is a method called gt() which is used to apply the Greater Than condition between elements of two pandas series objects.

The result of the gt() method is based on the comparison between elements of two series objects. The operation is equal to “element of called_series > element of passed_series”.

The resultant series object is filled with the boolean values(True Or False). True value indicates the element of called_series is Greater Than the element of passed_series. Revere for False.

Example 1

Given below is an example to compare two Pandas series objects by applying Greater Than condition using the gt() function:

# importing packages
import pandas as pd
import numpy as np

# Creating Pandas Series objects
series1 = pd.Series([34, np.nan, 82], index=['x', 'y', 'z'])
print('First series object:',series1)

series2 = pd.Series([np.nan, 12, 76], index=['x', 'y', 'z'])
print('Second series object:',series2)

# apply gt() method
result = series1.gt(series2)
print("Output:")
print(result)

Explanation

Initially, we have created the two pandas series objects using a list of integers, and the elements of the series contain some Nan values.

Output

The output is as follows −

First series object:
x    34.0
y    NaN
z    82.0
dtype: float64

Second series object:
x    NaN
y    12.0
z    76.0
dtype: float64

Output:
x    False
y    False
z    True
dtype: bool

We have applied the gt() method to compare the elements of two series objects, and we haven’t replaced the missing values, which is why we got False for x, y labeled elements of the output series.

Example 2

In the following example, we have applied the gt() method by replacing the missing values with an integer value 10.

# importing packages
import pandas as pd
import numpy as np

# Creating Pandas Series objects
series1 = pd.Series([100, 12, np.nan, 86], index=list("ABCD"))
print('First series object:',series1)

series2 = pd.Series([32, np.nan, 74, 61], index=list("ABCD"))
print('Second series object:',series2)

# apply gt() method
result = series1.gt(series2, fill_value=10)
print("Output:")
print(result)

Output

The output is as follows −

First series object:
A    100.0
B    12.0
C    NaN
D    86.0
dtype: float64

Second series object:
A    32.0
B    NaN
C    74.0
D    61.0
dtype: float64

Output:
A    True
B    True
C    False
D    True
dtype: bool

The gt() method replaces the missing values initially while executing the function and then performs the comparison operation.

raja
Updated on 07-Mar-2022 11:10:19

Advertisements