Get integer location, slice or boolean mask for requested label. Parameters ---------- key : label The key to check its location if it is present in the index. Returns ------- int if unique index, slice if monotonic index, else m
(self, key)
| 3599 | # Indexing Methods |
| 3600 | |
| 3601 | def get_loc(self, key): |
| 3602 | """ |
| 3603 | Get integer location, slice or boolean mask for requested label. |
| 3604 | |
| 3605 | Parameters |
| 3606 | ---------- |
| 3607 | key : label |
| 3608 | The key to check its location if it is present in the index. |
| 3609 | |
| 3610 | Returns |
| 3611 | ------- |
| 3612 | int if unique index, slice if monotonic index, else mask |
| 3613 | Integer location, slice or boolean mask. |
| 3614 | |
| 3615 | See Also |
| 3616 | -------- |
| 3617 | Index.get_slice_bound : Calculate slice bound that corresponds to |
| 3618 | given label. |
| 3619 | Index.get_indexer : Computes indexer and mask for new index given |
| 3620 | the current index. |
| 3621 | Index.get_non_unique : Returns indexer and masks for new index given |
| 3622 | the current index. |
| 3623 | Index.get_indexer_for : Returns an indexer even when non-unique. |
| 3624 | |
| 3625 | Examples |
| 3626 | -------- |
| 3627 | >>> unique_index = pd.Index(list("abc")) |
| 3628 | >>> unique_index.get_loc("b") |
| 3629 | 1 |
| 3630 | |
| 3631 | >>> monotonic_index = pd.Index(list("abbc")) |
| 3632 | >>> monotonic_index.get_loc("b") |
| 3633 | slice(1, 3, None) |
| 3634 | |
| 3635 | >>> non_monotonic_index = pd.Index(list("abcb")) |
| 3636 | >>> non_monotonic_index.get_loc("b") |
| 3637 | array([False, True, False, True]) |
| 3638 | """ |
| 3639 | casted_key = self._maybe_cast_indexer(key) |
| 3640 | try: |
| 3641 | return self._engine.get_loc(casted_key) |
| 3642 | except KeyError as err: |
| 3643 | if isinstance(casted_key, slice) or ( |
| 3644 | isinstance(casted_key, abc.Iterable) |
| 3645 | and any(isinstance(x, slice) for x in casted_key) |
| 3646 | ): |
| 3647 | raise InvalidIndexError(key) from err |
| 3648 | raise KeyError(key) from err |
| 3649 | except TypeError: |
| 3650 | # If we have a listlike key, _check_indexing_error will raise |
| 3651 | # InvalidIndexError. Otherwise we fall through and re-raise |
| 3652 | # the TypeError. |
| 3653 | self._check_indexing_error(key) |
| 3654 | raise |
| 3655 | |
| 3656 | @final |
| 3657 | def get_indexer( |