close

how to compare two string variables in pandas?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to compare two string variables in pandas in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

how to compare two string variables in pandas?

  1. how to compare two string variables in pandas?

    strip the spaces and lower the case:
    In [414]: test['A'].str.strip().str.lower() == test['B'].str.strip().str.lower()

  2. compare two string variables in pandas

    strip the spaces and lower the case:
    In [414]: test['A'].str.strip().str.lower() == test['B'].str.strip().str.lower()

Method 1

I think you can use str.lower and str.replace with arbitrary whitespace s/+:

test = pd.DataFrame({'A': ["john  doe", " john doe", 'John'], 
                     'B': [' john doe', 'eddie murphy', 'batman']})

print test['A'].str.lower().str.replace('s/+',"") == 
      test['B'].str.strip().str.replace('s/+',"")


0     True
1    False
2    False
dtype: bool

Method 2

strip the spaces and lower the case:

In [414]:
test['A'].str.strip().str.lower() == test['B'].str.strip().str.lower()

Out[414]:
0     True
1    False
2    False
dtype: bool

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read