Form the intersection of two Index objects. This returns a new Index with elements common to the index and `other`. Parameters ---------- other : Index or array-like An Index or an array-like object containing elements to form the in
(self, other, sort: bool = False)
| 3241 | |
| 3242 | @final |
| 3243 | def intersection(self, other, sort: bool = False): |
| 3244 | # default sort keyword is different here from other setops intentionally |
| 3245 | # done in GH#25063 |
| 3246 | """ |
| 3247 | Form the intersection of two Index objects. |
| 3248 | |
| 3249 | This returns a new Index with elements common to the index and `other`. |
| 3250 | |
| 3251 | Parameters |
| 3252 | ---------- |
| 3253 | other : Index or array-like |
| 3254 | An Index or an array-like object containing elements to form the |
| 3255 | intersection with the original Index. |
| 3256 | sort : True, False or None, default False |
| 3257 | Whether to sort the resulting index. |
| 3258 | |
| 3259 | * None : sort the result, except when `self` and `other` are equal |
| 3260 | or when the values cannot be compared. |
| 3261 | * False : do not sort the result. |
| 3262 | * True : Sort the result (which may raise TypeError). |
| 3263 | |
| 3264 | Returns |
| 3265 | ------- |
| 3266 | Index |
| 3267 | Returns a new Index object with elements common to both the original Index |
| 3268 | and the `other` Index. |
| 3269 | |
| 3270 | See Also |
| 3271 | -------- |
| 3272 | Index.union : Form the union of two Index objects. |
| 3273 | Index.difference : Return a new Index with elements of index not in other. |
| 3274 | Index.isin : Return a boolean array where the index values are in values. |
| 3275 | |
| 3276 | Examples |
| 3277 | -------- |
| 3278 | >>> idx1 = pd.Index([1, 2, 3, 4]) |
| 3279 | >>> idx2 = pd.Index([3, 4, 5, 6]) |
| 3280 | >>> idx1.intersection(idx2) |
| 3281 | Index([3, 4], dtype='int64') |
| 3282 | """ |
| 3283 | self._validate_sort_keyword(sort) |
| 3284 | self._assert_can_do_setop(other) |
| 3285 | other, result_name = self._convert_can_do_setop(other) |
| 3286 | |
| 3287 | if self.dtype != other.dtype: |
| 3288 | self, other = self._dti_setop_align_tzs(other, "intersection") |
| 3289 | |
| 3290 | if self.equals(other): |
| 3291 | if not self.is_unique: |
| 3292 | result = self.unique()._get_reconciled_name_object(other) |
| 3293 | else: |
| 3294 | result = self._get_reconciled_name_object(other) |
| 3295 | if sort is True: |
| 3296 | result = result.sort_values() |
| 3297 | return result |
| 3298 | |
| 3299 | if len(self) == 0 or len(other) == 0: |
| 3300 | # fastpath; we need to be careful about having commutativity |