diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 4e73ea348dfde..03da62983df22 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -264,6 +264,7 @@ Indexing - Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`) - Bug in :meth:`Series.__setitem__` where setting :attr:`NA` into a numeric-dtpye :class:`Series` would incorrectly upcast to object-dtype rather than treating the value as ``np.nan`` (:issue:`44199`) - Bug in getting a column from a DataFrame with an object-dtype row index with datetime-like values: the resulting Series now preserves the exact object-dtype Index from the parent DataFrame (:issue:`42950`) +- Bug in indexing on a :class:`DatetimeIndex` with a ``np.str_`` key incorrectly raising (:issue:`45580`) - Missing diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 559c56992f71e..942a07760b86e 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -291,7 +291,7 @@ def parse_datetime_string( return dt -def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None): +def parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None): """ Try hard to parse datetime string, leveraging dateutil plus some extra goodies like quarter recognition. @@ -312,6 +312,16 @@ def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None): str Describing resolution of parsed string. """ + if type(arg) is not str: + # GH#45580 np.str_ satisfies isinstance(obj, str) but if we annotate + # arg as "str" this raises here + if not isinstance(arg, np.str_): + raise TypeError( + "Argument 'arg' has incorrect type " + f"(expected str, got {type(arg).__name__})" + ) + arg = str(arg) + if is_offset_object(freq): freq = freq.rule_code diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 4b751fa7d5e3e..dac5a2cea4090 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -209,6 +209,13 @@ def test_loc_getitem_single_boolean_arg(self, obj, key, exp): class TestLocBaseIndependent: # Tests for loc that do not depend on subclassing Base + def test_loc_npstr(self): + # GH#45580 + df = DataFrame(index=date_range("2021", "2022")) + result = df.loc[np.array(["2021/6/1"])[0] :] + expected = df.iloc[151:] + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( "msg, key", [