Skip to content

Commit

Permalink
Use safe_sort in Index.intersection
Browse files Browse the repository at this point in the history
  • Loading branch information
reidy-p committed Jan 13, 2019
1 parent b85d131 commit d9e68be
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 22 deletions.
14 changes: 11 additions & 3 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2393,15 +2393,23 @@ def intersection(self, other, sort=True):
indexer = indexer[indexer != -1]

taken = other.take(indexer)
if self.name != other.name:
taken.name = None

if sort:
try:
taken = taken.sort_values()
taken = sorting.safe_sort(taken.values)
if self.name != other.name:
name = None
else:
name = self.name
return self._shallow_copy(taken, name=name)
except TypeError as e:
warnings.warn("%s, sort order is undefined for "
"incomparable objects" % e, RuntimeWarning,
stacklevel=3)

if self.name != other.name:
taken.name = None

return taken

def difference(self, other, sort=True):
Expand Down
22 changes: 3 additions & 19 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2356,17 +2356,8 @@ def test_intersection_base(self, sort):
first = index[:5]
second = index[:3]

if PY3 and sort:
# unorderable types
warn_type = RuntimeWarning
expected = Index([0, 'a', 1])
else:
warn_type = None
expected = Index([0, 1, 'a']) if sort else Index([0, 'a', 1])

with tm.assert_produces_warning(warn_type):
result = first.intersection(second, sort=sort)

expected = Index([0, 1, 'a']) if sort else Index([0, 'a', 1])
result = first.intersection(second, sort=sort)
tm.assert_index_equal(result, expected)

@pytest.mark.parametrize("klass", [
Expand All @@ -2378,14 +2369,7 @@ def test_intersection_different_type_base(self, klass, sort):
first = index[:5]
second = index[:3]

if PY3 and sort:
# unorderable types
warn_type = RuntimeWarning
else:
warn_type = None

with tm.assert_produces_warning(warn_type):
result = first.intersection(klass(second.values), sort=sort)
result = first.intersection(klass(second.values), sort=sort)
assert tm.equalContents(result, second)

@pytest.mark.parametrize("sort", [True, False])
Expand Down

0 comments on commit d9e68be

Please sign in to comment.