@@ -3098,7 +3098,6 @@ def _intersection(self, other: Index, sort=False):
3098
3098
intersection specialized to the case with matching dtypes.
3099
3099
"""
3100
3100
# TODO(EA): setops-refactor, clean all this up
3101
- lvals = self ._values
3102
3101
3103
3102
if self .is_monotonic and other .is_monotonic :
3104
3103
try :
@@ -3110,21 +3109,35 @@ def _intersection(self, other: Index, sort=False):
3110
3109
res = algos .unique1d (result )
3111
3110
return ensure_wrapped_if_datetimelike (res )
3112
3111
3113
- try :
3114
- indexer = other .get_indexer (lvals )
3115
- except InvalidIndexError :
3116
- # InvalidIndexError raised by get_indexer if non-unique
3117
- indexer , _ = other .get_indexer_non_unique (lvals )
3112
+ res_values = self ._intersection_via_get_indexer (other , sort = sort )
3113
+ res_values = _maybe_try_sort (res_values , sort )
3114
+ return res_values
3118
3115
3119
- mask = indexer != - 1
3120
- indexer = indexer .take (mask .nonzero ()[0 ])
3116
+ def _intersection_via_get_indexer (self , other : Index , sort ) -> ArrayLike :
3117
+ """
3118
+ Find the intersection of two Indexes using get_indexer.
3119
+
3120
+ Returns
3121
+ -------
3122
+ np.ndarray or ExtensionArray
3123
+ The returned array will be unique.
3124
+ """
3125
+ # Note: drop_duplicates vs unique matters for MultiIndex, though
3126
+ # it should not, see GH#41823
3127
+ left_unique = self .drop_duplicates ()
3128
+ right_unique = other .drop_duplicates ()
3121
3129
3122
- result = other .take (indexer ).unique ()._values
3123
- result = _maybe_try_sort (result , sort )
3130
+ indexer = left_unique .get_indexer (right_unique )
3131
+
3132
+ mask = indexer != - 1
3124
3133
3125
- # Intersection has to be unique
3126
- assert Index (result ).is_unique
3134
+ taker = indexer .take (mask .nonzero ()[0 ])
3135
+ if sort is False :
3136
+ # sort bc we want the elements in the same order they are in self
3137
+ # unnecessary in the case with sort=None bc we will sort later
3138
+ taker = np .sort (taker )
3127
3139
3140
+ result = left_unique .take (taker )._values
3128
3141
return result
3129
3142
3130
3143
@final
0 commit comments