Skip to content

Commit d3d58b1

Browse files
jbrockmendelyehoshuadimarsky
authored andcommitted
BUG: parse_time_string with np.str_ obj (pandas-dev#45626)
1 parent d170ddb commit d3d58b1

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ Indexing
267267
- 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`)
268268
- Bug in :meth:`DataFrame.mask` with ``inplace=True`` and ``ExtensionDtype`` columns incorrectly raising (:issue:`45577`)
269269
- 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`)
270+
- Bug in indexing on a :class:`DatetimeIndex` with a ``np.str_`` key incorrectly raising (:issue:`45580`)
270271
-
271272

272273
Missing

pandas/_libs/tslibs/parsing.pyx

+11-1
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ def parse_datetime_string(
291291
return dt
292292

293293

294-
def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None):
294+
def parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None):
295295
"""
296296
Try hard to parse datetime string, leveraging dateutil plus some extra
297297
goodies like quarter recognition.
@@ -312,6 +312,16 @@ def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None):
312312
str
313313
Describing resolution of parsed string.
314314
"""
315+
if type(arg) is not str:
316+
# GH#45580 np.str_ satisfies isinstance(obj, str) but if we annotate
317+
# arg as "str" this raises here
318+
if not isinstance(arg, np.str_):
319+
raise TypeError(
320+
"Argument 'arg' has incorrect type "
321+
f"(expected str, got {type(arg).__name__})"
322+
)
323+
arg = str(arg)
324+
315325
if is_offset_object(freq):
316326
freq = freq.rule_code
317327

pandas/tests/indexing/test_loc.py

+7
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,13 @@ def test_loc_getitem_single_boolean_arg(self, obj, key, exp):
209209

210210
class TestLocBaseIndependent:
211211
# Tests for loc that do not depend on subclassing Base
212+
def test_loc_npstr(self):
213+
# GH#45580
214+
df = DataFrame(index=date_range("2021", "2022"))
215+
result = df.loc[np.array(["2021/6/1"])[0] :]
216+
expected = df.iloc[151:]
217+
tm.assert_frame_equal(result, expected)
218+
212219
@pytest.mark.parametrize(
213220
"msg, key",
214221
[

0 commit comments

Comments
 (0)