Test whether Two pandas DataFrames are Equal in Python (Example Code)

This article demonstrates how to test whether two pandas DataFrames contain exactly the same values in Python.

Creation of Example Data

import pandas as pd                      # Import pandas
df_A = pd.DataFrame({'A':range(1, 5),    # Construct three pandas DataFrames
                     'B':[5, 5, 1, 3],
                     'C':range(15, 11, - 1)})
print(df_A)
#    A  B   C
# 0  1  5  15
# 1  2  5  14
# 2  3  1  13
# 3  4  3  12
df_B = pd.DataFrame({'A':range(1, 5),
                     'B':[5, 5, 1, 3],
                     'C':range(15, 11, - 1)})
print(df_B)
#    A  B   C
# 0  1  5  15
# 1  2  5  14
# 2  3  1  13
# 3  4  3  12
df_C = pd.DataFrame({'A':range(101, 105),
                     'B':[5, 5, 1, 3],
                     'C':range(15, 11, - 1)})
print(df_C)
#      A  B   C
# 0  101  5  15
# 1  102  5  14
# 2  103  1  13
# 3  104  3  12

Example: Compare Two pandas DataFrames for Equality Using equals() Function

print(df_A.equals(df_B))                 # df_A & df_B are equal?
# True
print(df_A.equals(df_C))                 # df_A & df_C are equal?
# False

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

Menu
Top