Skip to content

Commit a66efe1

Browse files
author
Sudam Ranasinghe
committed
BUG: Fix Index.intersection returning same instance when indexes are equal GH#63169
1 parent 7bf6660 commit a66efe1

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

pandas/core/indexes/base.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3286,6 +3286,11 @@ def intersection(self, other, sort: bool = False):
32863286
result = self.unique()._get_reconciled_name_object(other)
32873287
else:
32883288
result = self._get_reconciled_name_object(other)
3289+
3290+
# Always return a new instance on equality
3291+
if result is self:
3292+
result = self.copy()
3293+
32893294
if sort is True:
32903295
result = result.sort_values()
32913296
return result

pandas/tests/indexes/base_class/test_setops.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,3 +264,13 @@ def test_difference_object_type(self, diff_type, expected):
264264
result = getattr(idx1, diff_type)(idx2)
265265
expected = Index(expected)
266266
tm.assert_index_equal(result, expected)
267+
def test_intersection_returns_new_instance(self):
268+
idx1 = Index([0, 1])
269+
idx2 = Index([0, 1])
270+
result = idx1.intersection(idx2)
271+
272+
# Should be equal but NOT the same reference
273+
tm.assert_index_equal(result, idx1)
274+
print(idx1)
275+
assert result is not idx1
276+

0 commit comments

Comments
 (0)