|
16 | 16 | from pandas.core.dtypes.missing import isna
|
17 | 17 |
|
18 | 18 | from pandas.core.accessor import delegate_names
|
| 19 | +from pandas.core.algorithms import unique1d |
19 | 20 | from pandas.core.arrays import datetimelike as dtl
|
20 | 21 | from pandas.core.arrays.timedeltas import TimedeltaArray, _is_convertible_to_td
|
21 | 22 | from pandas.core.base import _shared_docs
|
@@ -475,27 +476,33 @@ def intersection(self, other):
|
475 | 476 | if len(other) == 0:
|
476 | 477 | return other
|
477 | 478 |
|
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 |
486 | 486 |
|
487 |
| - end = min(left[-1], right[-1]) |
488 |
| - start = right[0] |
| 487 | + end = min(left[-1], right[-1]) |
| 488 | + start = right[0] |
489 | 489 |
|
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) |
499 | 506 |
|
500 | 507 | def _maybe_promote(self, other):
|
501 | 508 | if other.inferred_type == 'timedelta':
|
|
0 commit comments