Skip to content
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

BUG: Index.difference not always returning a unique set of values #55113

Merged
merged 5 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ Interval

Indexing
^^^^^^^^
-
- Bug in :meth:`Index.difference` not returning a unique set of values when ``other`` is empty or ``other`` is considered non-comparable (:issue:`55113`)
-

Missing
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3598,14 +3598,14 @@ def difference(self, other, sort=None):

if len(other) == 0:
# Note: we do not (yet) sort even if sort=None GH#24959
result = self.rename(result_name)
result = self.unique().rename(result_name)
if sort is True:
return result.sort_values()
return result

if not self._should_compare(other):
# Nothing matches -> difference is everything
result = self.rename(result_name)
result = self.unique().rename(result_name)
if sort is True:
return result.sort_values()
return result
Expand Down
10 changes: 9 additions & 1 deletion pandas/tests/indexes/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -799,8 +799,16 @@ def test_difference_empty_arg(self, index, sort):
first = index[5:20]
first.name = "name"
result = first.difference([], sort)
expected = first.unique()
Copy link
Member

Choose a reason for hiding this comment

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

Could you construct a completely new Index for `expected instead (and below)?

Copy link
Member Author

Choose a reason for hiding this comment

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

Updated

tm.assert_index_equal(result, expected)

tm.assert_index_equal(result, first)
def test_difference_should_not_compare(self):
# GH 55113
left = Index([1, 1])
right = Index([True])
result = left.difference(right)
expected = left.unique()
tm.assert_index_equal(result, expected)

@pytest.mark.parametrize("index", ["string"], indirect=True)
def test_difference_identity(self, index, sort):
Expand Down