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 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
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 @@ -233,7 +233,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
14 changes: 12 additions & 2 deletions pandas/tests/indexes/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -796,11 +796,21 @@ def test_difference_name_preservation(self, index, second_name, expected, sort):
assert result.name == expected

def test_difference_empty_arg(self, index, sort):
first = index[5:20]
first = index.copy()
first = first[5:20]
first.name = "name"
result = first.difference([], sort)
expected = index[5:20].unique()
expected.name = "name"
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 = Index([1])
tm.assert_index_equal(result, expected)

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