diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 25234489167b2..12f522301e121 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -983,6 +983,7 @@ Datetimelike - Bug in :meth:`DataFrame.min` and :meth:`DataFrame.max` casting ``datetime64`` and ``timedelta64`` columns to ``float64`` and losing precision (:issue:`60850`) - Bug in :meth:`Dataframe.agg` with df with missing values resulting in IndexError (:issue:`58810`) - Bug in :meth:`DateOffset.rollback` (and subclass methods) with ``normalize=True`` rolling back one offset too long (:issue:`32616`) +- Bug in :meth:`DatetimeIndex.asof` with a string key giving incorrect results (:issue:`50946`) - Bug in :meth:`DatetimeIndex.is_year_start` and :meth:`DatetimeIndex.is_quarter_start` does not raise on Custom business days frequencies bigger then "1C" (:issue:`58664`) - Bug in :meth:`DatetimeIndex.is_year_start` and :meth:`DatetimeIndex.is_quarter_start` returning ``False`` on double-digit frequencies (:issue:`58523`) - Bug in :meth:`DatetimeIndex.union` and :meth:`DatetimeIndex.intersection` when ``unit`` was non-nanosecond (:issue:`59036`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 93b615fe7b101..72f7a1e086b60 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5675,7 +5675,7 @@ def asof(self, label): return self._na_value else: if isinstance(loc, slice): - loc = loc.indices(len(self))[-1] + return self[loc][-1] return self[loc] diff --git a/pandas/tests/indexes/datetimes/methods/test_asof.py b/pandas/tests/indexes/datetimes/methods/test_asof.py index dc92f533087bc..41415f2a37337 100644 --- a/pandas/tests/indexes/datetimes/methods/test_asof.py +++ b/pandas/tests/indexes/datetimes/methods/test_asof.py @@ -1,6 +1,7 @@ from datetime import timedelta from pandas import ( + DatetimeIndex, Index, Timestamp, date_range, @@ -28,3 +29,18 @@ def test_asof(self): dt = index[0].to_pydatetime() assert isinstance(index.asof(dt), Timestamp) + + def test_asof_datetime_string(self): + # GH#50946 + + dti = date_range("2021-08-05", "2021-08-10", freq="1D") + + key = "2021-08-09" + res = dti.asof(key) + exp = dti[4] + assert res == exp + + # add a non-midnight time caused a bug + dti2 = DatetimeIndex(list(dti) + ["2021-08-11 00:00:01"]) + res = dti2.asof(key) + assert res == exp