diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 721bcb0758992..34164a7cfdd5d 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -40,7 +40,7 @@ Deprecations Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- +- Performance improvement in :meth:`PeriodIndex.get_loc` using input from user (:issue:`29038`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 123353b620bfa..77d3a03039676 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -598,11 +598,9 @@ def get_loc(self, key, method=None, tolerance=None): TypeError If key is listlike or otherwise not hashable. """ - if isinstance(key, str): try: - asdt, parsed, reso = parse_time_string(key, self.freq) - key = asdt + key, parsed, reso = parse_time_string(key, self.freq) except DateParseError: # A string with invalid format raise KeyError(f"Cannot interpret '{key}' as period") @@ -613,6 +611,7 @@ def get_loc(self, key, method=None, tolerance=None): try: key = Period(key, freq=self.freq) + ordinal = key.ordinal if key is not NaT else key.value except ValueError: # we cannot construct the Period # as we have an invalid type @@ -620,18 +619,13 @@ def get_loc(self, key, method=None, tolerance=None): raise TypeError(f"'{key}' is an invalid key") raise KeyError(key) - ordinal = key.ordinal if key is not NaT else key.value + if tolerance is not None: + tolerance = self._convert_tolerance(tolerance, np.asarray(key)) + try: - return self._engine.get_loc(ordinal) + return self._int64index.get_loc(ordinal, method, tolerance) except KeyError: - - try: - if tolerance is not None: - tolerance = self._convert_tolerance(tolerance, np.asarray(key)) - return self._int64index.get_loc(ordinal, method, tolerance) - - except KeyError: - raise KeyError(key) + raise KeyError(key) def _maybe_cast_slice_bound(self, label, side, kind): """ diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index afc068d6696ef..d2328c1b41381 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -340,7 +340,7 @@ def test_memory_usage(self, indices): # RangeIndex, IntervalIndex # don't have engines if not isinstance(indices, (RangeIndex, IntervalIndex)): - assert result2 > result + assert result2 >= result if indices.inferred_type == "object": assert result3 > result2