Equality in Pandas DataFrames - Column Order Matters?

Usually you're going to want speedy tests and the sorting method can be brutally inefficient for larger indices (like if you were using rows instead of columns for this problem). The sort method is also susceptible to false negatives on non-unique indices.

Fortunately, pandas.util.testing.assert_frame_equal has since been updated with a check_like option. Set this to true and the ordering will not be considered in the test.

With non-unique indices, you'll get the cryptic ValueError: cannot reindex from a duplicate axis. This is raised by the under-the-hood reindex_like operation that rearranges one of the DataFrames to match the other's order. Reindexing is much faster than sorting as evidenced below.

import pandas as pd
from pandas.util.testing import assert_frame_equal

df  = pd.DataFrame(np.arange(1e6))
df1 = df.sample(frac=1, random_state=42)
df2 = df.sample(frac=1, random_state=43)

%timeit -n 1 -r 5 assert_frame_equal(df1.sort_index(), df2.sort_index())
## 5.73 s ± 329 ms per loop (mean ± std. dev. of 5 runs, 1 loop each)

%timeit -n 1 -r 5 assert_frame_equal(df1, df2, check_like=True)
## 1.04 s ± 237 ms per loop (mean ± std. dev. of 5 runs, 1 loop each)

For those who enjoy a good performance comparison plot:

Reindexing vs sorting on int and str indices (str even more drastic)


The most common intent is handled like this:

def assertFrameEqual(df1, df2, **kwds ):
    """ Assert that two dataframes are equal, ignoring ordering of columns"""
    from pandas.util.testing import assert_frame_equal
    return assert_frame_equal(df1.sort_index(axis=1), df2.sort_index(axis=1), check_names=True, **kwds )

Of course see pandas.util.testing.assert_frame_equal for other parameters you can pass


You could sort the columns using sort_index:

df1.sort_index(axis=1) == df2.sort_index(axis=1)

This will evaluate to a dataframe of all True values.


As @osa comments this fails for NaN's and isn't particularly robust either, in practise using something similar to @quant's answer is probably recommended (Note: we want a bool rather than raise if there's an issue):

def my_equal(df1, df2):
    from pandas.util.testing import assert_frame_equal
    try:
        assert_frame_equal(df1.sort_index(axis=1), df2.sort_index(axis=1), check_names=True)
        return True
    except (AssertionError, ValueError, TypeError):  perhaps something else?
        return False

def equal( df1, df2 ):
    """ Check if two DataFrames are equal, ignoring nans """
    return df1.fillna(1).sort_index(axis=1).eq(df2.fillna(1).sort_index(axis=1)).all().all()

Tags:

Python

Pandas