Skip to content

Commit 90d32f2

Browse files
committed
Add case to handle non-monontonic index without sorting
1 parent e0e7b51 commit 90d32f2

File tree

1 file changed

+26
-19
lines changed

1 file changed

+26
-19
lines changed

pandas/core/indexes/timedeltas.py

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from pandas.core.dtypes.missing import isna
1717

1818
from pandas.core.accessor import delegate_names
19+
from pandas.core.algorithms import unique1d
1920
from pandas.core.arrays import datetimelike as dtl
2021
from pandas.core.arrays.timedeltas import TimedeltaArray, _is_convertible_to_td
2122
from pandas.core.base import _shared_docs
@@ -475,27 +476,33 @@ def intersection(self, other):
475476
if len(other) == 0:
476477
return other
477478

478-
self = self.sort_values()
479-
other = other.sort_values()
480-
481-
# to make our life easier, "sort" the two ranges
482-
if self[0] <= other[0]:
483-
left, right = self, other
484-
else:
485-
left, right = other, self
479+
if self.is_monotonic:
480+
other = other.sort_values()
481+
# to make our life easier, "sort" the two ranges
482+
if self[0] <= other[0]:
483+
left, right = self, other
484+
else:
485+
left, right = other, self
486486

487-
end = min(left[-1], right[-1])
488-
start = right[0]
487+
end = min(left[-1], right[-1])
488+
start = right[0]
489489

490-
if end < start:
491-
return type(self)(data=[])
492-
else:
493-
lstart, lend = left.slice_locs(start, end)
494-
lslice = np.arange(lstart, lend)
495-
mask = [left_elem in right for left_elem in left[lstart: lend]]
496-
lslice = lslice[mask]
497-
left_chunk = left.values[lslice]
498-
return self._shallow_copy(left_chunk)
490+
if end < start:
491+
return type(self)(data=[])
492+
else:
493+
lstart, lend = left.slice_locs(start, end)
494+
lslice = np.arange(lstart, lend)
495+
mask = [left_elem in right for left_elem in left[lstart: lend]]
496+
lslice = lslice[mask]
497+
left_chunk = left.values[lslice]
498+
return self._shallow_copy(left_chunk)
499+
500+
indexer = other.get_indexer(self)
501+
indexer = indexer.take((indexer != -1).nonzero()[0])
502+
indexer = unique1d(indexer)
503+
504+
taken = other.take(indexer).values
505+
return self._shallow_copy(taken)
499506

500507
def _maybe_promote(self, other):
501508
if other.inferred_type == 'timedelta':

0 commit comments

Comments
 (0)