Skip to content

ENH: Fix output of assert_frame_equal if indexes differ and check_like=True #37479

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ Other enhancements
- :class:`Rolling` now supports the ``closed`` argument for fixed windows (:issue:`34315`)
- :class:`DatetimeIndex` and :class:`Series` with ``datetime64`` or ``datetime64tz`` dtypes now support ``std`` (:issue:`37436`)
- :class:`Window` now supports all Scipy window types in ``win_type`` with flexible keyword argument support (:issue:`34556`)
- :meth:`testing.assert_index_equal` now has a ``check_order`` parameter that allows indexes to be checked in an order-insensitive manner (:issue:`37478`)

.. _whatsnew_120.api_breaking.python:

Expand Down
20 changes: 17 additions & 3 deletions pandas/_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,7 @@ def assert_index_equal(
check_less_precise: Union[bool, int] = no_default,
check_exact: bool = True,
check_categorical: bool = True,
check_order: bool = True,
rtol: float = 1.0e-5,
Comment on lines +670 to 671
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably it is necessary to have the new parameter added to the very end of this function signature in order not to break any user's code, which for some reason use positional arguments.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the feedback.

I debated that and it looked like the rtol and atol params had been added before the (older) obj param, so I decided to put check_order with the other check params. That said, obj is not something that most user code would pass so perhaps the comparrison doesn't hold.

Happy to move the parameter.

I also just noticed that I forgot to add a versionadded tag (will do).

atol: float = 1.0e-8,
obj: str = "Index",
Expand Down Expand Up @@ -696,6 +697,12 @@ def assert_index_equal(
Whether to compare number exactly.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
check_order : bool, default True
Whether to compare the order of index entries as well as their values.
If True, both indexes must contain the same elements, in the same order.
If False, both indexes must contain the same elements, but in any order.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add a versionadded tag 1.2 here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, that's annoying, sorry.
I removed the versionadded tag when I moved the parameters :-(
I have put it back and rebased again.


.. versionadded:: 1.2.0
rtol : float, default 1e-5
Relative tolerance. Only used when check_exact is False.

Expand Down Expand Up @@ -762,6 +769,11 @@ def _get_ilevel_values(index, level):
msg3 = f"{len(right)}, {right}"
raise_assert_detail(obj, msg1, msg2, msg3)

# If order doesn't matter then sort the index entries
if not check_order:
left = left.sort_values()
right = right.sort_values()

# MultiIndex special comparison for little-friendly error messages
if left.nlevels > 1:
left = cast(MultiIndex, left)
Expand Down Expand Up @@ -1582,9 +1594,6 @@ def assert_frame_equal(
obj, f"{obj} shape mismatch", f"{repr(left.shape)}", f"{repr(right.shape)}"
)

if check_like:
left, right = left.reindex_like(right), right

if check_flags:
assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}"

Expand All @@ -1596,6 +1605,7 @@ def assert_frame_equal(
check_names=check_names,
check_exact=check_exact,
check_categorical=check_categorical,
check_order=not check_like,
rtol=rtol,
atol=atol,
obj=f"{obj}.index",
Expand All @@ -1609,11 +1619,15 @@ def assert_frame_equal(
check_names=check_names,
check_exact=check_exact,
check_categorical=check_categorical,
check_order=not check_like,
rtol=rtol,
atol=atol,
obj=f"{obj}.columns",
)

if check_like:
left, right = left.reindex_like(right), right

# compare by blocks
if by_blocks:
rblocks = right._to_dict_of_blocks()
Expand Down
10 changes: 6 additions & 4 deletions pandas/tests/util/test_assert_frame_equal.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ def test_empty_dtypes(check_dtype):
tm.assert_frame_equal(df1, df2, **kwargs)


def test_frame_equal_index_mismatch(obj_fixture):
@pytest.mark.parametrize("check_like", [True, False])
def test_frame_equal_index_mismatch(check_like, obj_fixture):
msg = f"""{obj_fixture}\\.index are different

{obj_fixture}\\.index values are different \\(33\\.33333 %\\)
Expand All @@ -156,10 +157,11 @@ def test_frame_equal_index_mismatch(obj_fixture):
df2 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "d"])

with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, obj=obj_fixture)
tm.assert_frame_equal(df1, df2, check_like=check_like, obj=obj_fixture)


def test_frame_equal_columns_mismatch(obj_fixture):
@pytest.mark.parametrize("check_like", [True, False])
def test_frame_equal_columns_mismatch(check_like, obj_fixture):
msg = f"""{obj_fixture}\\.columns are different

{obj_fixture}\\.columns values are different \\(50\\.0 %\\)
Expand All @@ -170,7 +172,7 @@ def test_frame_equal_columns_mismatch(obj_fixture):
df2 = DataFrame({"A": [1, 2, 3], "b": [4, 5, 6]}, index=["a", "b", "c"])

with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, obj=obj_fixture)
tm.assert_frame_equal(df1, df2, check_like=check_like, obj=obj_fixture)


def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture):
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/util/test_assert_index_equal.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,28 @@ def test_index_equal_values_too_far(check_exact, rtol):
tm.assert_index_equal(idx1, idx2, **kwargs)


@pytest.mark.parametrize("check_order", [True, False])
def test_index_equal_value_oder_mismatch(check_exact, rtol, check_order):
idx1 = Index([1, 2, 3])
idx2 = Index([3, 2, 1])

msg = """Index are different

Index values are different \\(66\\.66667 %\\)
\\[left\\]: Int64Index\\(\\[1, 2, 3\\], dtype='int64'\\)
\\[right\\]: Int64Index\\(\\[3, 2, 1\\], dtype='int64'\\)"""

if check_order:
with pytest.raises(AssertionError, match=msg):
tm.assert_index_equal(
idx1, idx2, check_exact=check_exact, rtol=rtol, check_order=True
)
else:
tm.assert_index_equal(
idx1, idx2, check_exact=check_exact, rtol=rtol, check_order=False
)


def test_index_equal_level_values_mismatch(check_exact, rtol):
idx1 = MultiIndex.from_tuples([("A", 2), ("A", 2), ("B", 3), ("B", 4)])
idx2 = MultiIndex.from_tuples([("A", 1), ("A", 2), ("B", 3), ("B", 4)])
Expand Down