How does the pandas series.gt() method work if the series object contains string-type elements?

PandasServer Side ProgrammingProgramming

The series.gt() method in the pandas constructor performs the Greater Than condition operation between the elements of a series object with another (example: with series, or with scalar, or with list-like object). And it is equal to “series > Other”.

Here we will see how the series.gt() method applies the Greater Than conditional operation on two input objects if their elements have string type data. In this case, the comparison is done with their ASCII values.

We only need to compare a string element with a corresponding element with the same data type. Otherwise, it will raise the TypeError. We cannot compare a string element of one series with an integer element of another series.

Example 1

In the following example, we have created two series objects by using the pandas.Series() constructor, the data type of elements contained in the series objects are strings.

# importing packages
import pandas as pd
import numpy as np

# Creating Pandas Series objects
series1 = pd.Series(['a', 'B', 'C', 'D'])
print('First series object:',series1)

series2 = pd.Series(['A', 'b', 'C', 'd'])
print('Second series object:',series2)

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

Output

The output is given below −

First series object:
0    a
1    B
2    C
3    D
dtype: object

Second series object:
0    A
1    b
2    C
3    d
dtype: object

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

The series.gt() method successfully applied the GreaterThan conditional operation between the elements of two series objects. Here, the GreaterThan condition was applied using their ASCII values.

Example 2

In this example, we have replaced the missing values (Nan) by using the fill_value parameter.

# importing packages
import pandas as pd
import numpy as np

# Creating Pandas Series objects
series1 = pd.Series(['a', np.nan, 'e', 'C', 'D'])
print('First series object:',series1)

series2 = pd.Series(['A', np.nan, 'E', 'C', 'd'])
print('Second series object:',series2)

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

Output

The output is as follows −

First series object:
0    a
1    NaN
2    e
3    C
4    D
dtype: object

Second series object:
0    A
1    NaN
2    E
3    C
4    d
dtype: object

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

The gt() method successfully replaced and applied the GreaterThen condition on the elements of two series objects.

raja
Updated on 07-Mar-2022 11:18:37

Advertisements