Compare Two Columns of pandas DataFrame in Python (3 Examples)

This tutorial explains how to compare two columns of a pandas DataFrame in the Python programming language.

Setting up the Examples

import pandas as pd                                # Import pandas library in Python
my_df = pd.DataFrame({'A':['a', 'b', 'c', 'd'],    # Construct pandas DataFrames
                      'B':['a', 'c', 'c', 'e']})
#    A  B
# 0  a  a
# 1  b  c
# 2  c  c
# 3  d  e

Example 1: How to Test which Elements in Columns are Equal

print(my_df['A'] == my_df['B'])                    # Which are equal?
# 0     True
# 1    False
# 2     True
# 3    False
# dtype: bool

Example 2: How to Test which Elements in Column A are also Contained in Column B

print(my_df['A'].isin(my_df['B']))                 # Which is in B?
# 0     True
# 1    False
# 2     True
# 3    False
# Name: A, dtype: bool

Example 3: How to Test If Each Element is the Same

print(my_df['A'].equals(my_df['B']))               # Are all equal?
# False

Related Tutorials & Further Resources

Have a look at the following Python programming language tutorials. They discuss topics such as descriptive statistics and naming data.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed