Skip to content
Open
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
5 changes: 5 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3286,6 +3286,11 @@ def intersection(self, other, sort: bool = False):
result = self.unique()._get_reconciled_name_object(other)
else:
result = self._get_reconciled_name_object(other)

# Always return a new instance on equality
if result is self:
result = self.copy()

if sort is True:
result = result.sort_values()
return result
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/indexes/base_class/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,13 @@ def test_difference_object_type(self, diff_type, expected):
result = getattr(idx1, diff_type)(idx2)
expected = Index(expected)
tm.assert_index_equal(result, expected)
def test_intersection_returns_new_instance(self):
idx1 = Index([0, 1])
idx2 = Index([0, 1])
result = idx1.intersection(idx2)

# Should be equal but NOT the same reference
tm.assert_index_equal(result, idx1)
print(idx1)
assert result is not idx1

Loading