What is the basic operation of the series.eq() method in pandas?


The series.eq() method in the pandas constructor is used to compare elements of the given series with others (maybe another series or a scalar value). As a result, It will return a new series object with boolean values.

The element-wise equal operation is done by using this eq() method. The boolean value True represents the equivalent value in the second series object. And remaining unequal values are represented by the boolean value False.

The parameters of the eq() method are other, fill_value, and level.

Example 1

In the following example, we will see how the eq() method compares elements of a series object with a scalar value.

# importing packages
import pandas as pd
import numpy as np

#create series
sr = pd.Series([24, 63, 21, np.nan, 24, 56, 24, 50])
print(sr)

# compare elements with a scalar value 24
result = sr.eq(24)
print(result)

Explanation

Initially, we have created a pandas Series by using a list of integers and some Nan values. After that, we applied the eq() method using a scalar value 24.

Output

The output is as follows −

0    24.0
1    63.0
2    21.0
3     NaN
4    24.0
5    56.0
6    24.0
7    50.0
dtype: float64

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

After running the above code we will get the following results, the eq() method compares the elements of the series object with a value 24. So, the equivalent values at index positions 0, 4, and 6 are represented by True and the remaining all are represented by False.

Example 2

Like we did in the previous example, here we are going to apply the eq() method on 2 series objects without changing any default parameter values.

# importing packages
import pandas as pd
import numpy as np

#create series
sr1 = pd.Series([np.nan, 61, 11, np.nan, 24, 56, 30, np.nan, 55])
print(sr1)

sr2 = pd.Series([0, 61, 22, np.nan, 24, 45, 30, 78, 93])
print(sr2)

# compare two series objects
result = sr1.eq(sr2)
print(result)

Output

The output is given below −

0     NaN
1    61.0
2    11.0
3     NaN
4    24.0
5    56.0
6    30.0
7     NaN
8    55.0
dtype: float64

0     0.0
1    61.0
2    22.0
3     NaN
4    24.0
5    45.0
6    30.0
7    78.0
8    93.0
dtype: float64

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

In the above output block, we can see both input series objects sr1, sr2, and also the resultant series object from the eq() method. The eq() method does not return true for Nan values due to this the value False is represented at the index location 3.

Updated on: 07-Mar-2022

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements