How to check the elements of a series object are Greater Than a scalar value?

PandasServer Side ProgrammingProgramming

By using the pandas series.gt() method we can check if the elements of a series object are Greater Than a scalar value or not. The gt() comparison operation is exactly equivalent to series > Other.

Here “other” can be any single or multiple element data structure, or list-like object, for example, scalar, sequence, or a Series.

To check the Greater Than comparison operation between elements of the given series with scalar, we need to send the scalar value as a parameter to the series.gt() method.

The method returns a series with the result of Greater than of a series with a scalar. The resultant series has boolean values. It indicates true for the elements which are Greater than the scalar. Otherwise, it will indicate False.

Example 1

In this following example, we have applied the Greater than condition operation between the elements series object and scalar value “50”.

# importing packages
import pandas as pd
import numpy as np

#create pandas series
series = pd.Series([89, 48, np.nan, 57, 25, np.nan, 62])
print(series)

# apply gt() method with a scalar value
result = series.gt(50)
print(result)

Output

The output is as follows −

0    89.0
1    48.0
2    NaN
3    57.0
4    25.0
5    NaN
6    62.0
dtype: float64

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

While comparing Nan with any other value the output will be False always. This can be rectified by replacing missing values by using the fill_value parameter.

Example 2

In the following example, we are replacing Missing values (Nan/NA) with an integer value 20 by using the fill_value parameter.

# importing packages
import pandas as pd
import numpy as np

#create pandas series
sr = pd.Series([1, np.nan, 11, 21, 31, 41, np.nan, 9])
print("Series object:")
print(sr)

# apply gt() method using a scalar value by replacing missing values
result = sr.gt(10, fill_value=20)
print("Output:")
print(result)

Output

The output is as follows −

Series object:
0    1.0
1    NaN
2    11.0
3    21.0
4    31.0
5    41.0
6    NaN
7    9.0
dtype: float64

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

In the above output block, We can observe that the Nan values are replaced with “20”. The first and last elements of the Output series object are less compared to the scalar value 10, and the remaining all are Greater Than the scalar value.

raja
Updated on 07-Mar-2022 11:07:31

Advertisements